Skip to content

C API: Detect buffer overflow in PyBytesWriter #156939

Description

@vstinner

PyBytesWriter gives a directy access to its content with PyBytesWriter_GetData(). The caller is responsible to handle correctly the buffer size and write the correct amount of bytes. But programming is hard, and mistakes are easy to do. I propose adding a mechanism to detect buffer overflow to help developers detecting bugs in in their code.

Example of bug:

    PyBytesWriter *writer = PyBytesWriter_Create(0);
    if (writer == NULL) {
        goto error;
    }
    if (PyBytesWriter_Grow(writer, 3) < 0) {
        goto error;
    }
    char *data = PyBytesWriter_GetData(writer);
    strcpy(data, "abc");

    return PyBytesWriter_Finish(writer);

This code allocates 3 bytes but writes 4 bytes because strcat() also writes a trailing NUL byte.

Linked PRs

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

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions