I’m reading the documentation for Memory Management in Python C extensions, and as far as I can tell, there doesn’t really seem to be much reason to use malloc rather than PyMem_Malloc. Say I want to allocate an array that isn’t to be exposed to Python source code and will be stored in an object that will be garbage collected. Is there any reason to use malloc?
I’m reading the documentation for Memory Management in Python C extensions , and as
Share
EDIT: Mixed
PyMem_MallocandPyObject_Malloccorrections; they are two different calls.Without the
PYMALLOC_DEBUGmacro activated,PyMem_Mallocis an alias of libc’smalloc(), having one special case: callingPyMem_Mallocto allocate zero bytes will return a non-NULL pointer, while malloc(zero_bytes) might return a NULL value or raise a system error (source code reference):Also, there is an advisory note on the
pymem.hheader file:Then, there are some Python specific tunings inside
PyMem_MallocPyObject_Malloc, a function used not only for C extensions but for all the dynamic allocations while running a Python program, like100*234,str(100)or10 + 4j:The previous
complex()instances are small objects allocated on a dedicated pool.Small objects (<256 bytes) allocation with
PyMem_MallocPyObject_Mallocis quite efficient since it’s done from a pool 8 bytes aligned blocks, existing one pool for each block size. There are also Pages and Arenas blocks for bigger allocations.This comment on the source code explains how the
PyObject_Malloccall is optimized:Pools, Pages and Arenas are optimizations intended to reduce external memory fragmentation of long running Python programs.
Check out the source code for the full detailed documentation on Python’s memory internals.