mirror of
https://github.com/python/cpython.git
synced 2026-06-28 03:41:13 +00:00
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))`.
(cherry picked from commit
|
||
|---|---|---|
| .. | ||
| clinic | ||
| abstract.c | ||
| buffer.c | ||
| bytes.c | ||
| code.c | ||
| codec.c | ||
| complex.c | ||
| config.c | ||
| datetime.c | ||
| dict.c | ||
| docstring.c | ||
| exceptions.c | ||
| file.c | ||
| float.c | ||
| frame.c | ||
| function.c | ||
| gc.c | ||
| getargs.c | ||
| hash.c | ||
| heaptype.c | ||
| immortal.c | ||
| import.c | ||
| list.c | ||
| long.c | ||
| mem.c | ||
| modsupport.c | ||
| module.c | ||
| monitoring.c | ||
| numbers.c | ||
| object.c | ||
| parts.h | ||
| pyatomic.c | ||
| README.txt | ||
| run.c | ||
| set.c | ||
| structmember.c | ||
| time.c | ||
| tuple.c | ||
| type.c | ||
| unicode.c | ||
| util.h | ||
| vectorcall.c | ||
| watchers.c | ||
| weakref.c | ||
Tests in this directory are compiled into the _testcapi extension. The main file for the extension is Modules/_testcapimodule.c, which calls `_PyTestCapi_Init_*` from these functions. General guideline when writing test code for C API. * Use Argument Clinic to minimise the amount of boilerplate code. * Add a newline between the argument spec and the docstring. * If a test description is needed, make sure the added docstring clearly and succinctly describes purpose of the function. * DRY, use the clone feature of Argument Clinic. * Try to avoid adding new interned strings; reuse existing parameter names if possible. Use the `as` feature of Argument Clinic to override the C variable name, if needed.