python / python/cpython

bytearray.resize() must not clear the object on error (memory allocation failure)

Open
#157,242 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

interpreter-core type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Python 3.15 reimplemented bytearray using an internal bytes object (to implement the bytearray.take_bytes() method). _PyBytes_Resize() is used internally to resize the bytearray object. Problem: if _PyBytes_Resize() fails, the bytearray object is cleared.

On Python 3.14, the bytearray is not cleared on resize failure.

The following example works on Python 3.14 but fails on Python 3.15.

import _testcapi

data = b'some data'
ba = bytearray(data)
try:
    try:
        _testcapi.set_nomemory(0)
        ba.resize(1024)
    except MemoryError:
        pass
    else:
        raise AssertionError("expect MemoryError")
finally:
    _testcapi.remove_mem_hooks()
if ba != data:
    raise AssertionError(f"{ba} != {data}")
Linked PRs
  • gh-157243
  • gh-157340
  • gh-157344
  • gh-157350
  • gh-157351
  • gh-157352
  • gh-157371
  • gh-157375
  • gh-157431
  • gh-157619
  • gh-157723
  • gh-157811

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the bytearray.resize() path and its use of _PyBytes_Resize(), then reproduce the provided _testcapi.set_nomemory() example. Done means a failed resize raises MemoryError while preserving the bytearray contents, with a regression test covering that behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.