Skip to content

Commit cb2377c

Browse files
committed
Fix resizing to 0 length / clearing leaving one byte alloc
1 parent bab7151 commit cb2377c

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

Lib/test/test_bytes.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1394,10 +1394,11 @@ def test_clear(self):
13941394
b = bytearray(b'abc')
13951395
b.clear()
13961396
self.assertEqual(b.__alloc__(), 0)
1397-
self.assertEqual(sys.getsizeof(b), 0)
1397+
base_size = sys.getsizeof(bytearray())
1398+
self.assertEqual(sys.getsizeof(b), base_size)
13981399
c = b.copy()
13991400
self.assertEqual(c.__alloc__(), 0)
1400-
self.assertEqual(sys.getsizeof(c), 0)
1401+
self.assertEqual(sys.getsizeof(c), base_size)
14011402

14021403
def test_copy(self):
14031404
b = bytearray(b'abc')
@@ -1466,7 +1467,8 @@ def test_take_bytes(self):
14661467
self.assertEqual(len(ba), 0)
14671468
self.assertEqual(ba, bytearray(b''))
14681469
self.assertEqual(ba.__alloc__(), 0)
1469-
self.assertEqual(sys.getsizeof(ba), 0)
1470+
base_size = sys.getsizeof(bytearray())
1471+
self.assertEqual(sys.getsizeof(ba), base_size)
14701472

14711473
# Positive and negative slicing.
14721474
ba = bytearray(b'abcdef')

Objects/bytearrayobject.c

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,11 @@ bytearray_resize_lock_held(PyObject *self, Py_ssize_t requested_size)
223223
if (size < alloc / 2) {
224224
/* Major downsize; resize down to exact size */
225225
alloc = size + 1;
226+
227+
/* If new size is 0; don't need to allocate one byte for null. */
228+
if (size == 0) {
229+
alloc = 0;
230+
}
226231
}
227232
else {
228233
/* Minor downsize; quick exit */
@@ -238,7 +243,7 @@ bytearray_resize_lock_held(PyObject *self, Py_ssize_t requested_size)
238243
alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
239244
}
240245
else {
241-
/* Major upsize; resize up to exact size */
246+
/* Major upsize; resize up to exact size. Upsize always means size > 0 */
242247
alloc = size + 1;
243248
}
244249
}

0 commit comments

Comments
 (0)