EDIT : mixed corrections PyMem_Malloc and PyObject_Malloc ; these are two different challenges.
Without the PYMALLOC_DEBUG macro PYMALLOC_DEBUG PyMem_Malloc is an alias of libc malloc() , which has one special case: a call to PyMem_Malloc to select null bytes returns a non-NULL pointer, whereas malloc (zero_bytes) may return NULL or raise a system error ( link to source code ):
/ * malloc. Note that nbytes == 0 tries to return a non-NULL * pointer from all other currently existing pointers. This may not be possible. * /
In addition, there is an advisory note in the pymem.h header file :
Never mix calls with PyMem_ with calls to the malloc / realloc / calloc / platform for free. For example, on Windows, different DLLs can have different heaps, and if you use PyMem_Malloc you will get memory from the heap used by the Python DLL; this can be a disaster if you are free (), which is right in your own extension. Instead, use PyMem_Free to ensure that Python can return memory to the correct heap. Like another example, in PYMALLOC_DEBUG mode, Python wraps all calls to all PyMem_ and PyObject_ memory functions in special debug shells that add additional information for debugging dynamic memory blocks. The system routines do not have a clue what to do with this material, and Python wrappers do not have a clue what to do with the raw blocks received directly then the system will be executed.
Then there are some Python settings inside PyMem_Malloc PyObject_Malloc , a function used not only for C-extensions, but for all dynamic distributions when starting a Python program, for example 100*234 , str(100) or 10 + 4j :
>>> id(10 + 4j) 139721697591440 >>> id(10 + 4j) 139721697591504 >>> id(10 + 4j) 139721697591440
Previous instances of complex() are small objects allocated in a dedicated pool.
Distributing small objects (<256 bytes) using PyMem_Malloc PyObject_Malloc quite efficient because it is made from a pool of 8 bytes with alignment, there is one pool for each block size. There are also Pages and Arenas blocks for large distributions.
This source comment explains how the PyObject_Malloc call is PyObject_Malloc :
Pools, pages, and arenas are optimizations designed to reduce fragmentation of the external memory of long Python programs.
Check out the source code for full detailed documentation on Python's internal internals.