Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2499,6 +2499,16 @@ def test_reinit_with_view(self):
self.assertRaises(BufferError, a.__init__, "x", "ascii")
self.assertEqual(a, b"")

def test_reinit_error(self):
# A failed __init__() must not leave uninitialized bytes in the
# object: it must be empty afterwards.
for source in ([256] * 100, (-1,) * 100, [0] * 50 + [1000],
(1, 2, 1 << 100)):
with self.subTest(source=source):
a = bytearray(b"abc")
self.assertRaises(ValueError, a.__init__, source)
self.assertEqual(a, b"")


class AssortedBytesTest(unittest.TestCase):
#
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix :meth:`!bytearray.__init__` leaving uninitialized memory in the object
when it fails on a :class:`list` or :class:`tuple` containing an integer not
in ``range(256)``. The object is now empty after the failed call.
6 changes: 6 additions & 0 deletions Objects/bytearrayobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1087,7 +1087,11 @@ bytearray___init___impl(PyByteArrayObject *self, PyObject *arg,
if (PyByteArray_Resize((PyObject *)self, size) < 0) goto fail;
if (PyBuffer_ToContiguous(PyByteArray_AS_STRING(self),
&view, size, 'C') < 0)
{
/* Don't expose the uninitialized bytes: reset to empty */
(void)PyByteArray_Resize((PyObject *)self, 0);
goto fail;
}
PyBuffer_Release(&view);
return 0;
fail:
Expand Down Expand Up @@ -1115,6 +1119,8 @@ bytearray___init___impl(PyByteArrayObject *self, PyObject *arg,
}
int rc = _getbytevalue(items[i], &value);
if (!rc) {
/* Don't expose the uninitialized bytes: reset to empty */
(void)PyByteArray_Resize((PyObject *)self, 0);
return -1;
}
s[i] = value;
Expand Down
Loading