Skip to content

bytearray reads and writes outside its buffer after del b[:n] fails with MemoryError #160303

Description

@gpshead

Bug report

Bug description:

If the allocation that shrinks the storage fails during del b[:n] (or b[:n] = shorter) on a bytearray, MemoryError is raised and the bytearray keeps its old length but starts n bytes before its buffer. Later reads return memory in front of the buffer and later writes modify it. bytearray_setslice_linear() undoes its ob_start advance on failure, but since gh-157242 (GH-157340) bytearray_resize_storage() has already moved the data and reset ob_start before the allocation is attempted.

import _testcapi

b = bytearray(b"A" * 100 + b"B" * 20)
_testcapi.set_nomemory(0, 1)
try:
    del b[:100]
except MemoryError:
    print("MemoryError")
finally:
    _testcapi.remove_mem_hooks()
print(len(b), b == b"A" * 100 + b"B" * 20)
print(bytes(b)[60:])

Expected 120 True and the original contents. On a debug build of main this prints

MemoryError
120 False
b'o\xfd\xfd\xfd\xfd\xfd\xfd\xfd\x01\x00\x00\x00\x00\x00\x00\x00\xa0\xdd\x86\xc8(^\x00\x00x\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xffBBBBBBBBBBBBBBBBBBBB'

The bytes before the Bs are allocator padding and the header of the internal bytes object. The 3.15 branch has the same bytearray_resize_storage() code; 3.14 is not affected.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs

Activity

  1. self-assigned this
    on Oct 22, 2026
  2. added
    type-bugAn unexpected behavior, bug, or error
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    on Oct 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions