Skip to content

io.StringIO crashes or returns garbage when used after a MemoryError #160324

Description

@gpshead

Bug report

Bug description:

When io.StringIO fails with MemoryError while converting its accumulated writes to the internal buffer (first readline(), iteration, partial read(), truncate() or a write that is not at the end), the text is dropped but the object keeps its old length. Later calls then index outside a 2-character buffer: they crash or return unrelated memory as text. getvalue() and a full read() can leave the object in the same state.

import io, resource
resource.setrlimit(resource.RLIMIT_DATA, (128 << 20, 128 << 20))
f = io.StringIO()
f.write("x" * (32 << 20))
f.seek(0)
try:
    f.readline()
except MemoryError:
    print("MemoryError")
print(f.seek(0, 2))
f.seek(0)
f.readline()

On a debug build of main this prints MemoryError, then 33554432, then dies with a segmentation fault in the second readline(). Expected: the object still holds its text or is empty, and the second call raises MemoryError or returns normally.

email.feedparser can reach this: FeedParser.close() after a feed() that raised MemoryError on a very long first line. gh-157242 was a similar state-after-MemoryError bug in bytearray.

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 a commit that references this issue on Oct 22, 2026
  3. added a commit that references this issue on Oct 31, 2026
  4. terryjreedy commented on Nov 1, 2026

    @terryjreedy
    Member

    Both backports failed tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

extension-modulesC modules in the Modules dirtopic-IOtype-crashA hard crash of the interpreter, possibly with a core dump

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions