Skip to content

Commit 5bf3765

Browse files
LarsHdpgeorge
authored andcommitted
py/objnamedtuple: Fix segfault with empty namedtuple.
The empty tuple is usually a constant object, but named tuples must be allocated to allow modification. Added explicit allocation to fix this. Also added a regression test to verify creating an empty named tuple works. Fixes issue adafruit#7870. Signed-off-by: Lars Haulin <[email protected]>
1 parent 2076f2e commit 5bf3765

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

py/objnamedtuple.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,10 @@ STATIC mp_obj_t namedtuple_make_new(const mp_obj_type_t *type_in, size_t n_args,
108108
#endif
109109
}
110110

111-
// Create a tuple and set the type to this namedtuple
112-
mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(num_fields, NULL));
113-
tuple->base.type = type_in;
111+
// Create a namedtuple with explicit malloc. Calling mp_obj_new_tuple
112+
// with num_fields=0 returns a read-only object.
113+
mp_obj_tuple_t *tuple = mp_obj_malloc_var(mp_obj_tuple_t, mp_obj_t, num_fields, type_in);
114+
tuple->len = num_fields;
114115

115116
// Copy the positional args into the first slots of the namedtuple
116117
memcpy(&tuple->items[0], args, sizeof(mp_obj_t) * n_args);

tests/basics/namedtuple1.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,8 @@
8585
# Not implemented so far
8686
#T2 = namedtuple("TupComma", "foo,bar")
8787
#t = T2(1, 2)
88+
89+
# Creating an empty namedtuple should not segfault
90+
T5 = namedtuple("TupEmpty", [])
91+
t = T5()
92+
print(t)

0 commit comments

Comments
 (0)