python / python/cpython

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

未关闭
#157,242 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

interpreter-core type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 bytearray.resize() 路径及其对 _PyBytes_Resize() 的使用入手,然后复现所提供的 _testcapi.set_nomemory() 示例。完成标准是:resize 失败时引发 MemoryError,同时保留 bytearray 的内容,并有一个覆盖该行为的回归测试。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
backend
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。