Skip to content

Commit ddf1aa9

Browse files
committed
list.pop(): Don't allow ->alloc drop to zero, which causes unexpected behavior.
1 parent 14d28be commit ddf1aa9

1 file changed

Lines changed: 8 additions & 4 deletions

File tree

py/objlist.c

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ static mp_obj_t mp_obj_new_list_iterator(mp_obj_list_t *list, int cur);
2323
static mp_obj_list_t *list_new(uint n);
2424
static mp_obj_t list_extend(mp_obj_t self_in, mp_obj_t arg_in);
2525

26+
// TODO: Move to mpconfig.h
27+
#define LIST_MIN_ALLOC 4
28+
2629
/******************************************************************************/
2730
/* list */
2831

@@ -181,6 +184,7 @@ mp_obj_t mp_obj_list_append(mp_obj_t self_in, mp_obj_t arg) {
181184
mp_obj_list_t *self = self_in;
182185
if (self->len >= self->alloc) {
183186
self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc * 2);
187+
assert(self->items);
184188
self->alloc *= 2;
185189
}
186190
self->items[self->len++] = arg;
@@ -215,7 +219,7 @@ static mp_obj_t list_pop(uint n_args, const mp_obj_t *args) {
215219
mp_obj_t ret = self->items[index];
216220
self->len -= 1;
217221
memcpy(self->items + index, self->items + index + 1, (self->len - index) * sizeof(mp_obj_t));
218-
if (self->alloc > 2 * self->len) {
222+
if (self->alloc > LIST_MIN_ALLOC && self->alloc > 2 * self->len) {
219223
self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc/2);
220224
self->alloc /= 2;
221225
}
@@ -267,8 +271,8 @@ static mp_obj_t list_clear(mp_obj_t self_in) {
267271
assert(MP_OBJ_IS_TYPE(self_in, &list_type));
268272
mp_obj_list_t *self = self_in;
269273
self->len = 0;
270-
self->items = m_renew(mp_obj_t, self->items, self->alloc, 4);
271-
self->alloc = 4;
274+
self->items = m_renew(mp_obj_t, self->items, self->alloc, LIST_MIN_ALLOC);
275+
self->alloc = LIST_MIN_ALLOC;
272276
return mp_const_none;
273277
}
274278

@@ -403,7 +407,7 @@ const mp_obj_type_t list_type = {
403407
static mp_obj_list_t *list_new(uint n) {
404408
mp_obj_list_t *o = m_new_obj(mp_obj_list_t);
405409
o->base.type = &list_type;
406-
o->alloc = n < 4 ? 4 : n;
410+
o->alloc = n < LIST_MIN_ALLOC ? LIST_MIN_ALLOC : n;
407411
o->len = n;
408412
o->items = m_new(mp_obj_t, o->alloc);
409413
return o;

0 commit comments

Comments
 (0)