Skip to content

Commit 9275c18

Browse files
committed
py/map: Fix bugs with deletion of elements from OrderedDict.
There were 2 bugs, now fixed by this patch: - after deleting an element the len of the dict did not decrease by 1 - after deleting an element searching through the dict could lead to a seg fault due to there being an MP_OBJ_SENTINEL in the ordered array
1 parent 845a80a commit 9275c18

1 file changed

Lines changed: 8 additions & 3 deletions

File tree

py/map.c

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -178,16 +178,21 @@ mp_map_elem_t *mp_map_lookup(mp_map_t *map, mp_obj_t index, mp_map_lookup_kind_t
178178
for (mp_map_elem_t *elem = &map->table[0], *top = &map->table[map->used]; elem < top; elem++) {
179179
if (elem->key == index || (!compare_only_ptrs && mp_obj_equal(elem->key, index))) {
180180
if (MP_UNLIKELY(lookup_kind == MP_MAP_LOOKUP_REMOVE_IF_FOUND)) {
181-
elem->key = MP_OBJ_SENTINEL;
182-
// keep elem->value so that caller can access it if needed
181+
// remove the found element by moving the rest of the array down
182+
mp_obj_t value = elem->value;
183+
--map->used;
184+
memmove(elem, elem + 1, (top - elem - 1) * sizeof(*elem));
185+
// put the found element after the end so the caller can access it if needed
186+
elem = &map->table[map->used];
187+
elem->key = MP_OBJ_NULL;
188+
elem->value = value;
183189
}
184190
return elem;
185191
}
186192
}
187193
if (MP_LIKELY(lookup_kind != MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)) {
188194
return NULL;
189195
}
190-
// TODO shrink array down over any previously-freed slots
191196
if (map->used == map->alloc) {
192197
// TODO: Alloc policy
193198
map->alloc += 4;

0 commit comments

Comments
 (0)