diff --git a/py/objstr.c b/py/objstr.c index ed9ab4e45b..13d957105a 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -223,7 +223,10 @@ STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size } if (MP_OBJ_IS_SMALL_INT(args[0])) { - uint len = MP_OBJ_SMALL_INT_VALUE(args[0]); + mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[0]); + if (len < 0) { + mp_raise_ValueError(NULL); + } vstr_t vstr; vstr_init_len(&vstr, len); memset(vstr.buf, 0, len); diff --git a/tests/basics/bytes.py b/tests/basics/bytes.py index 1d97e6b16f..0b6b14fa55 100644 --- a/tests/basics/bytes.py +++ b/tests/basics/bytes.py @@ -56,3 +56,9 @@ print(x[0], x[1], x[2], x[3]) print(bytes([128, 255])) # For sequence of unknown len print(bytes(iter([128, 255]))) + +# Shouldn't be able to make bytes with negative length +try: + bytes(-1) +except ValueError: + print('ValueError')