]> git.ipfire.org Git - thirdparty/Python/cpython.git/commit
gh-151297: Fix undefined behavior in `_PyObject_MiRealloc` (GH-151358)
authorMatt Wozniski <mwozniski@bloomberg.net>
Fri, 12 Jun 2026 01:21:04 +0000 (21:21 -0400)
committerGitHub <noreply@github.com>
Fri, 12 Jun 2026 01:21:04 +0000 (21:21 -0400)
commitc37599200f688538efa34a49f262a9a4a899a953
tree1c326b7cf23ad5c10e3162ba889037eb47663dd5
parent80f9467434cecbc4e97b853b3876de13e75aec38
gh-151297: Fix undefined behavior in `_PyObject_MiRealloc` (GH-151358)

The standard says that a call to `memcpy` must pass a valid source and
destination pointer even if the size is 0, so we must avoid calling
`memcpy` when our source pointer is NULL. If we don't, an optimizing
compiler can decide that the pointer must be non-NULL based on the
presence of UB, and optimize out checks for null pointers.

Specifically, note that the standard says:

    Where an argument declared as size_t n specifies the length of the
    array for a function, n can have the value zero on a call to that
    function. Unless explicitly stated otherwise in the description of
    a particular function in this subclause, pointer arguments on such
    a call shall still have valid values, as described in 7.1.4.

And section 7.1.4 says:

    If an argument to a function has an invalid value (such as a value
    outside the domain of the function, or a pointer outside the address
    space of the program, or a null pointer, or a pointer to
    non-modifiable storage when the corresponding parameter is not
    const-qualified) or a type (after default argument promotion) not
    expected by a function with a variable number of arguments, the
    behavior is undefined.

The specification for `memcpy` doesn't state that it's allowed to be
called with null pointers, and Linux's `/usr/include/string.h` declares
`memcpy` as `__nonnull ((1, 2))`.
Misc/NEWS.d/next/Core_and_Builtins/2026-06-11-16-03-23.gh-issue-151297.NGPkUM.rst [new file with mode: 0644]
Modules/_testcapi/mem.c
Objects/obmalloc.c