Skip to content

struct.Struct.pack_into with '0p' modifies a byte outside its zero-sized representation #158762

Description

@augusto-rehfeldt

Bug report

Bug description:

Documented behaviour: Python 3.14 library documentation, struct.Struct.pack_into: "Write the packed representation of the values v1, v2, ... into the writable buffer buffer starting at offset." The format documentation states: "The 'p' format character encodes a 'Pascal string', meaning a short variable-length string stored in a fixed number of bytes, given by the count."

Expected: The buffer remains b'\xfe'.

Actual: pack_into changes the buffer to b'\x00' despite Struct.size being zero.

import struct

s = struct.Struct('0p')
b, offset, v = bytearray(b'\xfe'), 0, b''
inp = repr((b, offset, v))
expected = bytes(b)  # A zero-byte representation changes no bytes.
if not (s.size == 0 and isinstance(b, bytearray) and b
        and isinstance(offset, int) and 0 <= offset < len(b)
        and isinstance(v, bytes)):
    print('REFUTATION REJECTED: invalid input')
else:
    try:
        s.pack_into(b, offset, v)
    except Exception as e:
        print('REFUTATION REJECTED:', repr(e))
    else:
        actual = bytes(b)
        if actual != expected:
            print('REFUTATION CONFIRMED:', inp,
                  'actual:', repr(actual), 'expected:', repr(expected))
        else:
            print('REFUTATION REJECTED: buffer unchanged')

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

REFUTATION CONFIRMED: (bytearray(b'\xfe'), 0, b'') actual: b'\x00' expected: b'\xfe'

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-182950-c2

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