vstr_init_len: Don't crash if (size_t)-1 is passed

In this unusual case, (len + 1) is zero, the allocation in vstr_init
succeeds (allocating 1 byte), and then the caller is likely to erroneously
access outside the allocated region, for instance with a memset().

This could be triggered with os.urandom(-1) after it was converted to use
mp_obj_new_bytes_of_zeros.
This commit is contained in:
Jeff Epler 2020-01-08 09:42:44 -06:00
parent 22644d33c9
commit 5baaac55ce

View File

@ -50,6 +50,8 @@ void vstr_init(vstr_t *vstr, size_t alloc) {
// Init the vstr so it allocs exactly enough ram to hold a null-terminated // Init the vstr so it allocs exactly enough ram to hold a null-terminated
// string of the given length, and set the length. // string of the given length, and set the length.
void vstr_init_len(vstr_t *vstr, size_t len) { void vstr_init_len(vstr_t *vstr, size_t len) {
if(len == SIZE_MAX)
m_malloc_fail(len);
vstr_init(vstr, len + 1); vstr_init(vstr, len + 1);
vstr->len = len; vstr->len = len;
} }