Skip to content

struct.pack_into corrupts an 's' value when source and destination are the same bytearray #158761

Description

@augusto-rehfeldt

Bug report

Bug description:

Documented behaviour: Python struct documentation, struct.pack_into: "Pack the values v1, v2, ... according to the format string format and write the packed bytes into the writable buffer buffer starting at position offset." The format-character notes also state: "For the 's' format character, the count is interpreted as the length of the bytes."

Expected: b'A'

Actual: b'\x00'

import struct

b = bytearray(b'A')
fmt, offset = '1s', 0
given = repr((fmt, b, offset, b))
if not isinstance(b, bytearray) or len(b) != struct.calcsize(fmt):
    print('REFUTATION REJECTED: invalid input')
else:
    expected = bytes(b)  # Exactly one byte: no padding or truncation.
    struct.pack_into(fmt, b, offset, b)
    actual = bytes(b)
    if actual != expected:
        print('REFUTATION CONFIRMED:', given, 'actual=', actual, 'expected=', expected)
    else:
        print('REFUTATION REJECTED: actual equals documented expectation')

Output on Python 3.14.6 (Windows-11-10.0.26220-SP0), standard library struct:

REFUTATION CONFIRMED: ('1s', bytearray(b'A'), 0, bytearray(b'A')) actual= b'\x00' expected= b'A'

This report was found and written by an automated property-testing tool I run (bugforge). The reproducer above was executed and its output is pasted unedited; no person reviewed the report before it was filed. The search script is in https://github.com/augusto-rehfeldt/bugforge-results/tree/main/struct-20261003-122508-c3

CPython versions tested on:

3.14

Operating systems tested on:

Windows

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions