Skip to content

bytearray.__init__() leaves stale bytes when it fails on a list or tuple #160179

Closed

Description

@gpshead

Bug report

Bug description:

The list/tuple fast path in bytearray.__init__() resizes the object to len(arg) before converting the items. When an exact int is outside range(256) it raises ValueError without undoing the resize, so an object that outlives the failed call (a re-initialized bytearray, or a subclass catching the error from super().__init__()) keeps the full length, with bytes that were never written.

b = bytearray(b'abc')
try:
    b.__init__([1, 2, 300])
except ValueError:
    pass
print(len(b), b)

This prints a length of 3; the last byte is leftover heap content (0xcd on a debug build). Expected 0 bytearray(b''), which is what a non-int item ([1, 2, 1.5]) or an iterator (iter([1, 2, 300]), which leaves b'\x01\x02') gives. With [300] * n the whole object is stale data from a recently freed block. The buffer branch has the same shape when PyBuffer_ToContiguous() fails.

The fast path dates back to gh-91149 (3.11).

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
  3. added a commit that references this issue on Oct 22, 2026
  4. added 2 commits that reference this issue 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