17db96d56Sopenharmony_ci.. highlight:: c
27db96d56Sopenharmony_ci
37db96d56Sopenharmony_ci
47db96d56Sopenharmony_ci.. _memory:
57db96d56Sopenharmony_ci
67db96d56Sopenharmony_ci*****************
77db96d56Sopenharmony_ciMemory Management
87db96d56Sopenharmony_ci*****************
97db96d56Sopenharmony_ci
107db96d56Sopenharmony_ci.. sectionauthor:: Vladimir Marangozov <Vladimir.Marangozov@inrialpes.fr>
117db96d56Sopenharmony_ci
127db96d56Sopenharmony_ci
137db96d56Sopenharmony_ci
147db96d56Sopenharmony_ci.. _memoryoverview:
157db96d56Sopenharmony_ci
167db96d56Sopenharmony_ciOverview
177db96d56Sopenharmony_ci========
187db96d56Sopenharmony_ci
197db96d56Sopenharmony_ciMemory management in Python involves a private heap containing all Python
207db96d56Sopenharmony_ciobjects and data structures. The management of this private heap is ensured
217db96d56Sopenharmony_ciinternally by the *Python memory manager*.  The Python memory manager has
227db96d56Sopenharmony_cidifferent components which deal with various dynamic storage management aspects,
237db96d56Sopenharmony_cilike sharing, segmentation, preallocation or caching.
247db96d56Sopenharmony_ci
257db96d56Sopenharmony_ciAt the lowest level, a raw memory allocator ensures that there is enough room in
267db96d56Sopenharmony_cithe private heap for storing all Python-related data by interacting with the
277db96d56Sopenharmony_cimemory manager of the operating system. On top of the raw memory allocator,
287db96d56Sopenharmony_ciseveral object-specific allocators operate on the same heap and implement
297db96d56Sopenharmony_cidistinct memory management policies adapted to the peculiarities of every object
307db96d56Sopenharmony_citype. For example, integer objects are managed differently within the heap than
317db96d56Sopenharmony_cistrings, tuples or dictionaries because integers imply different storage
327db96d56Sopenharmony_cirequirements and speed/space tradeoffs. The Python memory manager thus delegates
337db96d56Sopenharmony_cisome of the work to the object-specific allocators, but ensures that the latter
347db96d56Sopenharmony_cioperate within the bounds of the private heap.
357db96d56Sopenharmony_ci
367db96d56Sopenharmony_ciIt is important to understand that the management of the Python heap is
377db96d56Sopenharmony_ciperformed by the interpreter itself and that the user has no control over it,
387db96d56Sopenharmony_cieven if they regularly manipulate object pointers to memory blocks inside that
397db96d56Sopenharmony_ciheap.  The allocation of heap space for Python objects and other internal
407db96d56Sopenharmony_cibuffers is performed on demand by the Python memory manager through the Python/C
417db96d56Sopenharmony_ciAPI functions listed in this document.
427db96d56Sopenharmony_ci
437db96d56Sopenharmony_ci.. index::
447db96d56Sopenharmony_ci   single: malloc()
457db96d56Sopenharmony_ci   single: calloc()
467db96d56Sopenharmony_ci   single: realloc()
477db96d56Sopenharmony_ci   single: free()
487db96d56Sopenharmony_ci
497db96d56Sopenharmony_ciTo avoid memory corruption, extension writers should never try to operate on
507db96d56Sopenharmony_ciPython objects with the functions exported by the C library: :c:func:`malloc`,
517db96d56Sopenharmony_ci:c:func:`calloc`, :c:func:`realloc` and :c:func:`free`.  This will result in  mixed
527db96d56Sopenharmony_cicalls between the C allocator and the Python memory manager with fatal
537db96d56Sopenharmony_ciconsequences, because they implement different algorithms and operate on
547db96d56Sopenharmony_cidifferent heaps.  However, one may safely allocate and release memory blocks
557db96d56Sopenharmony_ciwith the C library allocator for individual purposes, as shown in the following
567db96d56Sopenharmony_ciexample::
577db96d56Sopenharmony_ci
587db96d56Sopenharmony_ci   PyObject *res;
597db96d56Sopenharmony_ci   char *buf = (char *) malloc(BUFSIZ); /* for I/O */
607db96d56Sopenharmony_ci
617db96d56Sopenharmony_ci   if (buf == NULL)
627db96d56Sopenharmony_ci       return PyErr_NoMemory();
637db96d56Sopenharmony_ci   ...Do some I/O operation involving buf...
647db96d56Sopenharmony_ci   res = PyBytes_FromString(buf);
657db96d56Sopenharmony_ci   free(buf); /* malloc'ed */
667db96d56Sopenharmony_ci   return res;
677db96d56Sopenharmony_ci
687db96d56Sopenharmony_ciIn this example, the memory request for the I/O buffer is handled by the C
697db96d56Sopenharmony_cilibrary allocator. The Python memory manager is involved only in the allocation
707db96d56Sopenharmony_ciof the bytes object returned as a result.
717db96d56Sopenharmony_ci
727db96d56Sopenharmony_ciIn most situations, however, it is recommended to allocate memory from the
737db96d56Sopenharmony_ciPython heap specifically because the latter is under control of the Python
747db96d56Sopenharmony_cimemory manager. For example, this is required when the interpreter is extended
757db96d56Sopenharmony_ciwith new object types written in C. Another reason for using the Python heap is
767db96d56Sopenharmony_cithe desire to *inform* the Python memory manager about the memory needs of the
777db96d56Sopenharmony_ciextension module. Even when the requested memory is used exclusively for
787db96d56Sopenharmony_ciinternal, highly specific purposes, delegating all memory requests to the Python
797db96d56Sopenharmony_cimemory manager causes the interpreter to have a more accurate image of its
807db96d56Sopenharmony_cimemory footprint as a whole. Consequently, under certain circumstances, the
817db96d56Sopenharmony_ciPython memory manager may or may not trigger appropriate actions, like garbage
827db96d56Sopenharmony_cicollection, memory compaction or other preventive procedures. Note that by using
837db96d56Sopenharmony_cithe C library allocator as shown in the previous example, the allocated memory
847db96d56Sopenharmony_cifor the I/O buffer escapes completely the Python memory manager.
857db96d56Sopenharmony_ci
867db96d56Sopenharmony_ci.. seealso::
877db96d56Sopenharmony_ci
887db96d56Sopenharmony_ci   The :envvar:`PYTHONMALLOC` environment variable can be used to configure
897db96d56Sopenharmony_ci   the memory allocators used by Python.
907db96d56Sopenharmony_ci
917db96d56Sopenharmony_ci   The :envvar:`PYTHONMALLOCSTATS` environment variable can be used to print
927db96d56Sopenharmony_ci   statistics of the :ref:`pymalloc memory allocator <pymalloc>` every time a
937db96d56Sopenharmony_ci   new pymalloc object arena is created, and on shutdown.
947db96d56Sopenharmony_ci
957db96d56Sopenharmony_ciAllocator Domains
967db96d56Sopenharmony_ci=================
977db96d56Sopenharmony_ci
987db96d56Sopenharmony_ci.. _allocator-domains:
997db96d56Sopenharmony_ci
1007db96d56Sopenharmony_ciAll allocating functions belong to one of three different "domains" (see also
1017db96d56Sopenharmony_ci:c:type:`PyMemAllocatorDomain`). These domains represent different allocation
1027db96d56Sopenharmony_cistrategies and are optimized for different purposes. The specific details on
1037db96d56Sopenharmony_cihow every domain allocates memory or what internal functions each domain calls
1047db96d56Sopenharmony_ciis considered an implementation detail, but for debugging purposes a simplified
1057db96d56Sopenharmony_citable can be found at :ref:`here <default-memory-allocators>`. There is no hard
1067db96d56Sopenharmony_cirequirement to use the memory returned by the allocation functions belonging to
1077db96d56Sopenharmony_cia given domain for only the purposes hinted by that domain (although this is the
1087db96d56Sopenharmony_cirecommended practice). For example, one could use the memory returned by
1097db96d56Sopenharmony_ci:c:func:`PyMem_RawMalloc` for allocating Python objects or the memory returned
1107db96d56Sopenharmony_ciby :c:func:`PyObject_Malloc` for allocating memory for buffers.
1117db96d56Sopenharmony_ci
1127db96d56Sopenharmony_ciThe three allocation domains are:
1137db96d56Sopenharmony_ci
1147db96d56Sopenharmony_ci* Raw domain: intended for allocating memory for general-purpose memory
1157db96d56Sopenharmony_ci  buffers where the allocation *must* go to the system allocator or where the
1167db96d56Sopenharmony_ci  allocator can operate without the :term:`GIL`. The memory is requested directly
1177db96d56Sopenharmony_ci  to the system.
1187db96d56Sopenharmony_ci
1197db96d56Sopenharmony_ci* "Mem" domain: intended for allocating memory for Python buffers and
1207db96d56Sopenharmony_ci  general-purpose memory buffers where the allocation must be performed with
1217db96d56Sopenharmony_ci  the :term:`GIL` held. The memory is taken from the Python private heap.
1227db96d56Sopenharmony_ci
1237db96d56Sopenharmony_ci* Object domain: intended for allocating memory belonging to Python objects. The
1247db96d56Sopenharmony_ci  memory is taken from the Python private heap.
1257db96d56Sopenharmony_ci
1267db96d56Sopenharmony_ciWhen freeing memory previously allocated by the allocating functions belonging to a
1277db96d56Sopenharmony_cigiven domain,the matching specific deallocating functions must be used. For example,
1287db96d56Sopenharmony_ci:c:func:`PyMem_Free` must be used to free memory allocated using :c:func:`PyMem_Malloc`.
1297db96d56Sopenharmony_ci
1307db96d56Sopenharmony_ciRaw Memory Interface
1317db96d56Sopenharmony_ci====================
1327db96d56Sopenharmony_ci
1337db96d56Sopenharmony_ciThe following function sets are wrappers to the system allocator. These
1347db96d56Sopenharmony_cifunctions are thread-safe, the :term:`GIL <global interpreter lock>` does not
1357db96d56Sopenharmony_cineed to be held.
1367db96d56Sopenharmony_ci
1377db96d56Sopenharmony_ciThe :ref:`default raw memory allocator <default-memory-allocators>` uses
1387db96d56Sopenharmony_cithe following functions: :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc`
1397db96d56Sopenharmony_ciand :c:func:`free`; call ``malloc(1)`` (or ``calloc(1, 1)``) when requesting
1407db96d56Sopenharmony_cizero bytes.
1417db96d56Sopenharmony_ci
1427db96d56Sopenharmony_ci.. versionadded:: 3.4
1437db96d56Sopenharmony_ci
1447db96d56Sopenharmony_ci.. c:function:: void* PyMem_RawMalloc(size_t n)
1457db96d56Sopenharmony_ci
1467db96d56Sopenharmony_ci   Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the
1477db96d56Sopenharmony_ci   allocated memory, or ``NULL`` if the request fails.
1487db96d56Sopenharmony_ci
1497db96d56Sopenharmony_ci   Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as
1507db96d56Sopenharmony_ci   if ``PyMem_RawMalloc(1)`` had been called instead. The memory will not have
1517db96d56Sopenharmony_ci   been initialized in any way.
1527db96d56Sopenharmony_ci
1537db96d56Sopenharmony_ci
1547db96d56Sopenharmony_ci.. c:function:: void* PyMem_RawCalloc(size_t nelem, size_t elsize)
1557db96d56Sopenharmony_ci
1567db96d56Sopenharmony_ci   Allocates *nelem* elements each whose size in bytes is *elsize* and returns
1577db96d56Sopenharmony_ci   a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the
1587db96d56Sopenharmony_ci   request fails. The memory is initialized to zeros.
1597db96d56Sopenharmony_ci
1607db96d56Sopenharmony_ci   Requesting zero elements or elements of size zero bytes returns a distinct
1617db96d56Sopenharmony_ci   non-``NULL`` pointer if possible, as if ``PyMem_RawCalloc(1, 1)`` had been
1627db96d56Sopenharmony_ci   called instead.
1637db96d56Sopenharmony_ci
1647db96d56Sopenharmony_ci   .. versionadded:: 3.5
1657db96d56Sopenharmony_ci
1667db96d56Sopenharmony_ci
1677db96d56Sopenharmony_ci.. c:function:: void* PyMem_RawRealloc(void *p, size_t n)
1687db96d56Sopenharmony_ci
1697db96d56Sopenharmony_ci   Resizes the memory block pointed to by *p* to *n* bytes. The contents will
1707db96d56Sopenharmony_ci   be unchanged to the minimum of the old and the new sizes.
1717db96d56Sopenharmony_ci
1727db96d56Sopenharmony_ci   If *p* is ``NULL``, the call is equivalent to ``PyMem_RawMalloc(n)``; else if
1737db96d56Sopenharmony_ci   *n* is equal to zero, the memory block is resized but is not freed, and the
1747db96d56Sopenharmony_ci   returned pointer is non-``NULL``.
1757db96d56Sopenharmony_ci
1767db96d56Sopenharmony_ci   Unless *p* is ``NULL``, it must have been returned by a previous call to
1777db96d56Sopenharmony_ci   :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc` or
1787db96d56Sopenharmony_ci   :c:func:`PyMem_RawCalloc`.
1797db96d56Sopenharmony_ci
1807db96d56Sopenharmony_ci   If the request fails, :c:func:`PyMem_RawRealloc` returns ``NULL`` and *p*
1817db96d56Sopenharmony_ci   remains a valid pointer to the previous memory area.
1827db96d56Sopenharmony_ci
1837db96d56Sopenharmony_ci
1847db96d56Sopenharmony_ci.. c:function:: void PyMem_RawFree(void *p)
1857db96d56Sopenharmony_ci
1867db96d56Sopenharmony_ci   Frees the memory block pointed to by *p*, which must have been returned by a
1877db96d56Sopenharmony_ci   previous call to :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc` or
1887db96d56Sopenharmony_ci   :c:func:`PyMem_RawCalloc`.  Otherwise, or if ``PyMem_RawFree(p)`` has been
1897db96d56Sopenharmony_ci   called before, undefined behavior occurs.
1907db96d56Sopenharmony_ci
1917db96d56Sopenharmony_ci   If *p* is ``NULL``, no operation is performed.
1927db96d56Sopenharmony_ci
1937db96d56Sopenharmony_ci
1947db96d56Sopenharmony_ci.. _memoryinterface:
1957db96d56Sopenharmony_ci
1967db96d56Sopenharmony_ciMemory Interface
1977db96d56Sopenharmony_ci================
1987db96d56Sopenharmony_ci
1997db96d56Sopenharmony_ciThe following function sets, modeled after the ANSI C standard, but specifying
2007db96d56Sopenharmony_cibehavior when requesting zero bytes, are available for allocating and releasing
2017db96d56Sopenharmony_cimemory from the Python heap.
2027db96d56Sopenharmony_ci
2037db96d56Sopenharmony_ciThe :ref:`default memory allocator <default-memory-allocators>` uses the
2047db96d56Sopenharmony_ci:ref:`pymalloc memory allocator <pymalloc>`.
2057db96d56Sopenharmony_ci
2067db96d56Sopenharmony_ci.. warning::
2077db96d56Sopenharmony_ci
2087db96d56Sopenharmony_ci   The :term:`GIL <global interpreter lock>` must be held when using these
2097db96d56Sopenharmony_ci   functions.
2107db96d56Sopenharmony_ci
2117db96d56Sopenharmony_ci.. versionchanged:: 3.6
2127db96d56Sopenharmony_ci
2137db96d56Sopenharmony_ci   The default allocator is now pymalloc instead of system :c:func:`malloc`.
2147db96d56Sopenharmony_ci
2157db96d56Sopenharmony_ci.. c:function:: void* PyMem_Malloc(size_t n)
2167db96d56Sopenharmony_ci
2177db96d56Sopenharmony_ci   Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the
2187db96d56Sopenharmony_ci   allocated memory, or ``NULL`` if the request fails.
2197db96d56Sopenharmony_ci
2207db96d56Sopenharmony_ci   Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as
2217db96d56Sopenharmony_ci   if ``PyMem_Malloc(1)`` had been called instead. The memory will not have
2227db96d56Sopenharmony_ci   been initialized in any way.
2237db96d56Sopenharmony_ci
2247db96d56Sopenharmony_ci
2257db96d56Sopenharmony_ci.. c:function:: void* PyMem_Calloc(size_t nelem, size_t elsize)
2267db96d56Sopenharmony_ci
2277db96d56Sopenharmony_ci   Allocates *nelem* elements each whose size in bytes is *elsize* and returns
2287db96d56Sopenharmony_ci   a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the
2297db96d56Sopenharmony_ci   request fails. The memory is initialized to zeros.
2307db96d56Sopenharmony_ci
2317db96d56Sopenharmony_ci   Requesting zero elements or elements of size zero bytes returns a distinct
2327db96d56Sopenharmony_ci   non-``NULL`` pointer if possible, as if ``PyMem_Calloc(1, 1)`` had been called
2337db96d56Sopenharmony_ci   instead.
2347db96d56Sopenharmony_ci
2357db96d56Sopenharmony_ci   .. versionadded:: 3.5
2367db96d56Sopenharmony_ci
2377db96d56Sopenharmony_ci
2387db96d56Sopenharmony_ci.. c:function:: void* PyMem_Realloc(void *p, size_t n)
2397db96d56Sopenharmony_ci
2407db96d56Sopenharmony_ci   Resizes the memory block pointed to by *p* to *n* bytes. The contents will be
2417db96d56Sopenharmony_ci   unchanged to the minimum of the old and the new sizes.
2427db96d56Sopenharmony_ci
2437db96d56Sopenharmony_ci   If *p* is ``NULL``, the call is equivalent to ``PyMem_Malloc(n)``; else if *n*
2447db96d56Sopenharmony_ci   is equal to zero, the memory block is resized but is not freed, and the
2457db96d56Sopenharmony_ci   returned pointer is non-``NULL``.
2467db96d56Sopenharmony_ci
2477db96d56Sopenharmony_ci   Unless *p* is ``NULL``, it must have been returned by a previous call to
2487db96d56Sopenharmony_ci   :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or :c:func:`PyMem_Calloc`.
2497db96d56Sopenharmony_ci
2507db96d56Sopenharmony_ci   If the request fails, :c:func:`PyMem_Realloc` returns ``NULL`` and *p* remains
2517db96d56Sopenharmony_ci   a valid pointer to the previous memory area.
2527db96d56Sopenharmony_ci
2537db96d56Sopenharmony_ci
2547db96d56Sopenharmony_ci.. c:function:: void PyMem_Free(void *p)
2557db96d56Sopenharmony_ci
2567db96d56Sopenharmony_ci   Frees the memory block pointed to by *p*, which must have been returned by a
2577db96d56Sopenharmony_ci   previous call to :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or
2587db96d56Sopenharmony_ci   :c:func:`PyMem_Calloc`.  Otherwise, or if ``PyMem_Free(p)`` has been called
2597db96d56Sopenharmony_ci   before, undefined behavior occurs.
2607db96d56Sopenharmony_ci
2617db96d56Sopenharmony_ci   If *p* is ``NULL``, no operation is performed.
2627db96d56Sopenharmony_ci
2637db96d56Sopenharmony_ciThe following type-oriented macros are provided for convenience.  Note  that
2647db96d56Sopenharmony_ci*TYPE* refers to any C type.
2657db96d56Sopenharmony_ci
2667db96d56Sopenharmony_ci
2677db96d56Sopenharmony_ci.. c:function:: TYPE* PyMem_New(TYPE, size_t n)
2687db96d56Sopenharmony_ci
2697db96d56Sopenharmony_ci   Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of
2707db96d56Sopenharmony_ci   memory.  Returns a pointer cast to :c:expr:`TYPE*`.  The memory will not have
2717db96d56Sopenharmony_ci   been initialized in any way.
2727db96d56Sopenharmony_ci
2737db96d56Sopenharmony_ci
2747db96d56Sopenharmony_ci.. c:function:: TYPE* PyMem_Resize(void *p, TYPE, size_t n)
2757db96d56Sopenharmony_ci
2767db96d56Sopenharmony_ci   Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n *
2777db96d56Sopenharmony_ci   sizeof(TYPE))`` bytes.  Returns a pointer cast to :c:expr:`TYPE*`. On return,
2787db96d56Sopenharmony_ci   *p* will be a pointer to the new memory area, or ``NULL`` in the event of
2797db96d56Sopenharmony_ci   failure.
2807db96d56Sopenharmony_ci
2817db96d56Sopenharmony_ci   This is a C preprocessor macro; *p* is always reassigned.  Save the original
2827db96d56Sopenharmony_ci   value of *p* to avoid losing memory when handling errors.
2837db96d56Sopenharmony_ci
2847db96d56Sopenharmony_ci
2857db96d56Sopenharmony_ci.. c:function:: void PyMem_Del(void *p)
2867db96d56Sopenharmony_ci
2877db96d56Sopenharmony_ci   Same as :c:func:`PyMem_Free`.
2887db96d56Sopenharmony_ci
2897db96d56Sopenharmony_ciIn addition, the following macro sets are provided for calling the Python memory
2907db96d56Sopenharmony_ciallocator directly, without involving the C API functions listed above. However,
2917db96d56Sopenharmony_cinote that their use does not preserve binary compatibility across Python
2927db96d56Sopenharmony_civersions and is therefore deprecated in extension modules.
2937db96d56Sopenharmony_ci
2947db96d56Sopenharmony_ci* ``PyMem_MALLOC(size)``
2957db96d56Sopenharmony_ci* ``PyMem_NEW(type, size)``
2967db96d56Sopenharmony_ci* ``PyMem_REALLOC(ptr, size)``
2977db96d56Sopenharmony_ci* ``PyMem_RESIZE(ptr, type, size)``
2987db96d56Sopenharmony_ci* ``PyMem_FREE(ptr)``
2997db96d56Sopenharmony_ci* ``PyMem_DEL(ptr)``
3007db96d56Sopenharmony_ci
3017db96d56Sopenharmony_ci
3027db96d56Sopenharmony_ciObject allocators
3037db96d56Sopenharmony_ci=================
3047db96d56Sopenharmony_ci
3057db96d56Sopenharmony_ciThe following function sets, modeled after the ANSI C standard, but specifying
3067db96d56Sopenharmony_cibehavior when requesting zero bytes, are available for allocating and releasing
3077db96d56Sopenharmony_cimemory from the Python heap.
3087db96d56Sopenharmony_ci
3097db96d56Sopenharmony_ci.. note::
3107db96d56Sopenharmony_ci    There is no guarantee that the memory returned by these allocators can be
3117db96d56Sopenharmony_ci    successfully cast to a Python object when intercepting the allocating
3127db96d56Sopenharmony_ci    functions in this domain by the methods described in
3137db96d56Sopenharmony_ci    the :ref:`Customize Memory Allocators <customize-memory-allocators>` section.
3147db96d56Sopenharmony_ci
3157db96d56Sopenharmony_ciThe :ref:`default object allocator <default-memory-allocators>` uses the
3167db96d56Sopenharmony_ci:ref:`pymalloc memory allocator <pymalloc>`.
3177db96d56Sopenharmony_ci
3187db96d56Sopenharmony_ci.. warning::
3197db96d56Sopenharmony_ci
3207db96d56Sopenharmony_ci   The :term:`GIL <global interpreter lock>` must be held when using these
3217db96d56Sopenharmony_ci   functions.
3227db96d56Sopenharmony_ci
3237db96d56Sopenharmony_ci.. c:function:: void* PyObject_Malloc(size_t n)
3247db96d56Sopenharmony_ci
3257db96d56Sopenharmony_ci   Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the
3267db96d56Sopenharmony_ci   allocated memory, or ``NULL`` if the request fails.
3277db96d56Sopenharmony_ci
3287db96d56Sopenharmony_ci   Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as
3297db96d56Sopenharmony_ci   if ``PyObject_Malloc(1)`` had been called instead. The memory will not have
3307db96d56Sopenharmony_ci   been initialized in any way.
3317db96d56Sopenharmony_ci
3327db96d56Sopenharmony_ci
3337db96d56Sopenharmony_ci.. c:function:: void* PyObject_Calloc(size_t nelem, size_t elsize)
3347db96d56Sopenharmony_ci
3357db96d56Sopenharmony_ci   Allocates *nelem* elements each whose size in bytes is *elsize* and returns
3367db96d56Sopenharmony_ci   a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the
3377db96d56Sopenharmony_ci   request fails. The memory is initialized to zeros.
3387db96d56Sopenharmony_ci
3397db96d56Sopenharmony_ci   Requesting zero elements or elements of size zero bytes returns a distinct
3407db96d56Sopenharmony_ci   non-``NULL`` pointer if possible, as if ``PyObject_Calloc(1, 1)`` had been called
3417db96d56Sopenharmony_ci   instead.
3427db96d56Sopenharmony_ci
3437db96d56Sopenharmony_ci   .. versionadded:: 3.5
3447db96d56Sopenharmony_ci
3457db96d56Sopenharmony_ci
3467db96d56Sopenharmony_ci.. c:function:: void* PyObject_Realloc(void *p, size_t n)
3477db96d56Sopenharmony_ci
3487db96d56Sopenharmony_ci   Resizes the memory block pointed to by *p* to *n* bytes. The contents will be
3497db96d56Sopenharmony_ci   unchanged to the minimum of the old and the new sizes.
3507db96d56Sopenharmony_ci
3517db96d56Sopenharmony_ci   If *p* is ``NULL``, the call is equivalent to ``PyObject_Malloc(n)``; else if *n*
3527db96d56Sopenharmony_ci   is equal to zero, the memory block is resized but is not freed, and the
3537db96d56Sopenharmony_ci   returned pointer is non-``NULL``.
3547db96d56Sopenharmony_ci
3557db96d56Sopenharmony_ci   Unless *p* is ``NULL``, it must have been returned by a previous call to
3567db96d56Sopenharmony_ci   :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or :c:func:`PyObject_Calloc`.
3577db96d56Sopenharmony_ci
3587db96d56Sopenharmony_ci   If the request fails, :c:func:`PyObject_Realloc` returns ``NULL`` and *p* remains
3597db96d56Sopenharmony_ci   a valid pointer to the previous memory area.
3607db96d56Sopenharmony_ci
3617db96d56Sopenharmony_ci
3627db96d56Sopenharmony_ci.. c:function:: void PyObject_Free(void *p)
3637db96d56Sopenharmony_ci
3647db96d56Sopenharmony_ci   Frees the memory block pointed to by *p*, which must have been returned by a
3657db96d56Sopenharmony_ci   previous call to :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or
3667db96d56Sopenharmony_ci   :c:func:`PyObject_Calloc`.  Otherwise, or if ``PyObject_Free(p)`` has been called
3677db96d56Sopenharmony_ci   before, undefined behavior occurs.
3687db96d56Sopenharmony_ci
3697db96d56Sopenharmony_ci   If *p* is ``NULL``, no operation is performed.
3707db96d56Sopenharmony_ci
3717db96d56Sopenharmony_ci
3727db96d56Sopenharmony_ci.. _default-memory-allocators:
3737db96d56Sopenharmony_ci
3747db96d56Sopenharmony_ciDefault Memory Allocators
3757db96d56Sopenharmony_ci=========================
3767db96d56Sopenharmony_ci
3777db96d56Sopenharmony_ciDefault memory allocators:
3787db96d56Sopenharmony_ci
3797db96d56Sopenharmony_ci===============================  ====================  ==================  =====================  ====================
3807db96d56Sopenharmony_ciConfiguration                    Name                  PyMem_RawMalloc     PyMem_Malloc           PyObject_Malloc
3817db96d56Sopenharmony_ci===============================  ====================  ==================  =====================  ====================
3827db96d56Sopenharmony_ciRelease build                    ``"pymalloc"``        ``malloc``          ``pymalloc``           ``pymalloc``
3837db96d56Sopenharmony_ciDebug build                      ``"pymalloc_debug"``  ``malloc`` + debug  ``pymalloc`` + debug   ``pymalloc`` + debug
3847db96d56Sopenharmony_ciRelease build, without pymalloc  ``"malloc"``          ``malloc``          ``malloc``             ``malloc``
3857db96d56Sopenharmony_ciDebug build, without pymalloc    ``"malloc_debug"``    ``malloc`` + debug  ``malloc`` + debug     ``malloc`` + debug
3867db96d56Sopenharmony_ci===============================  ====================  ==================  =====================  ====================
3877db96d56Sopenharmony_ci
3887db96d56Sopenharmony_ciLegend:
3897db96d56Sopenharmony_ci
3907db96d56Sopenharmony_ci* Name: value for :envvar:`PYTHONMALLOC` environment variable.
3917db96d56Sopenharmony_ci* ``malloc``: system allocators from the standard C library, C functions:
3927db96d56Sopenharmony_ci  :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` and :c:func:`free`.
3937db96d56Sopenharmony_ci* ``pymalloc``: :ref:`pymalloc memory allocator <pymalloc>`.
3947db96d56Sopenharmony_ci* "+ debug": with :ref:`debug hooks on the Python memory allocators
3957db96d56Sopenharmony_ci  <pymem-debug-hooks>`.
3967db96d56Sopenharmony_ci* "Debug build": :ref:`Python build in debug mode <debug-build>`.
3977db96d56Sopenharmony_ci
3987db96d56Sopenharmony_ci.. _customize-memory-allocators:
3997db96d56Sopenharmony_ci
4007db96d56Sopenharmony_ciCustomize Memory Allocators
4017db96d56Sopenharmony_ci===========================
4027db96d56Sopenharmony_ci
4037db96d56Sopenharmony_ci.. versionadded:: 3.4
4047db96d56Sopenharmony_ci
4057db96d56Sopenharmony_ci.. c:type:: PyMemAllocatorEx
4067db96d56Sopenharmony_ci
4077db96d56Sopenharmony_ci   Structure used to describe a memory block allocator. The structure has
4087db96d56Sopenharmony_ci   the following fields:
4097db96d56Sopenharmony_ci
4107db96d56Sopenharmony_ci   +----------------------------------------------------------+---------------------------------------+
4117db96d56Sopenharmony_ci   | Field                                                    | Meaning                               |
4127db96d56Sopenharmony_ci   +==========================================================+=======================================+
4137db96d56Sopenharmony_ci   | ``void *ctx``                                            | user context passed as first argument |
4147db96d56Sopenharmony_ci   +----------------------------------------------------------+---------------------------------------+
4157db96d56Sopenharmony_ci   | ``void* malloc(void *ctx, size_t size)``                 | allocate a memory block               |
4167db96d56Sopenharmony_ci   +----------------------------------------------------------+---------------------------------------+
4177db96d56Sopenharmony_ci   | ``void* calloc(void *ctx, size_t nelem, size_t elsize)`` | allocate a memory block initialized   |
4187db96d56Sopenharmony_ci   |                                                          | with zeros                            |
4197db96d56Sopenharmony_ci   +----------------------------------------------------------+---------------------------------------+
4207db96d56Sopenharmony_ci   | ``void* realloc(void *ctx, void *ptr, size_t new_size)`` | allocate or resize a memory block     |
4217db96d56Sopenharmony_ci   +----------------------------------------------------------+---------------------------------------+
4227db96d56Sopenharmony_ci   | ``void free(void *ctx, void *ptr)``                      | free a memory block                   |
4237db96d56Sopenharmony_ci   +----------------------------------------------------------+---------------------------------------+
4247db96d56Sopenharmony_ci
4257db96d56Sopenharmony_ci   .. versionchanged:: 3.5
4267db96d56Sopenharmony_ci      The :c:type:`PyMemAllocator` structure was renamed to
4277db96d56Sopenharmony_ci      :c:type:`PyMemAllocatorEx` and a new ``calloc`` field was added.
4287db96d56Sopenharmony_ci
4297db96d56Sopenharmony_ci
4307db96d56Sopenharmony_ci.. c:type:: PyMemAllocatorDomain
4317db96d56Sopenharmony_ci
4327db96d56Sopenharmony_ci   Enum used to identify an allocator domain. Domains:
4337db96d56Sopenharmony_ci
4347db96d56Sopenharmony_ci   .. c:macro:: PYMEM_DOMAIN_RAW
4357db96d56Sopenharmony_ci
4367db96d56Sopenharmony_ci      Functions:
4377db96d56Sopenharmony_ci
4387db96d56Sopenharmony_ci      * :c:func:`PyMem_RawMalloc`
4397db96d56Sopenharmony_ci      * :c:func:`PyMem_RawRealloc`
4407db96d56Sopenharmony_ci      * :c:func:`PyMem_RawCalloc`
4417db96d56Sopenharmony_ci      * :c:func:`PyMem_RawFree`
4427db96d56Sopenharmony_ci
4437db96d56Sopenharmony_ci   .. c:macro:: PYMEM_DOMAIN_MEM
4447db96d56Sopenharmony_ci
4457db96d56Sopenharmony_ci      Functions:
4467db96d56Sopenharmony_ci
4477db96d56Sopenharmony_ci      * :c:func:`PyMem_Malloc`,
4487db96d56Sopenharmony_ci      * :c:func:`PyMem_Realloc`
4497db96d56Sopenharmony_ci      * :c:func:`PyMem_Calloc`
4507db96d56Sopenharmony_ci      * :c:func:`PyMem_Free`
4517db96d56Sopenharmony_ci
4527db96d56Sopenharmony_ci   .. c:macro:: PYMEM_DOMAIN_OBJ
4537db96d56Sopenharmony_ci
4547db96d56Sopenharmony_ci      Functions:
4557db96d56Sopenharmony_ci
4567db96d56Sopenharmony_ci      * :c:func:`PyObject_Malloc`
4577db96d56Sopenharmony_ci      * :c:func:`PyObject_Realloc`
4587db96d56Sopenharmony_ci      * :c:func:`PyObject_Calloc`
4597db96d56Sopenharmony_ci      * :c:func:`PyObject_Free`
4607db96d56Sopenharmony_ci
4617db96d56Sopenharmony_ci.. c:function:: void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
4627db96d56Sopenharmony_ci
4637db96d56Sopenharmony_ci   Get the memory block allocator of the specified domain.
4647db96d56Sopenharmony_ci
4657db96d56Sopenharmony_ci
4667db96d56Sopenharmony_ci.. c:function:: void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
4677db96d56Sopenharmony_ci
4687db96d56Sopenharmony_ci   Set the memory block allocator of the specified domain.
4697db96d56Sopenharmony_ci
4707db96d56Sopenharmony_ci   The new allocator must return a distinct non-``NULL`` pointer when requesting
4717db96d56Sopenharmony_ci   zero bytes.
4727db96d56Sopenharmony_ci
4737db96d56Sopenharmony_ci   For the :c:data:`PYMEM_DOMAIN_RAW` domain, the allocator must be
4747db96d56Sopenharmony_ci   thread-safe: the :term:`GIL <global interpreter lock>` is not held when the
4757db96d56Sopenharmony_ci   allocator is called.
4767db96d56Sopenharmony_ci
4777db96d56Sopenharmony_ci   If the new allocator is not a hook (does not call the previous allocator),
4787db96d56Sopenharmony_ci   the :c:func:`PyMem_SetupDebugHooks` function must be called to reinstall the
4797db96d56Sopenharmony_ci   debug hooks on top on the new allocator.
4807db96d56Sopenharmony_ci
4817db96d56Sopenharmony_ci   See also :c:member:`PyPreConfig.allocator` and :ref:`Preinitialize Python
4827db96d56Sopenharmony_ci   with PyPreConfig <c-preinit>`.
4837db96d56Sopenharmony_ci
4847db96d56Sopenharmony_ci   .. warning::
4857db96d56Sopenharmony_ci
4867db96d56Sopenharmony_ci       :c:func:`PyMem_SetAllocator` does have the following contract:
4877db96d56Sopenharmony_ci
4887db96d56Sopenharmony_ci        * It can be called after :c:func:`Py_PreInitialize` and before
4897db96d56Sopenharmony_ci          :c:func:`Py_InitializeFromConfig` to install a custom memory
4907db96d56Sopenharmony_ci          allocator. There are no restrictions over the installed allocator
4917db96d56Sopenharmony_ci          other than the ones imposed by the domain (for instance, the Raw
4927db96d56Sopenharmony_ci          Domain allows the allocator to be called without the GIL held). See
4937db96d56Sopenharmony_ci          :ref:`the section on allocator domains <allocator-domains>` for more
4947db96d56Sopenharmony_ci          information.
4957db96d56Sopenharmony_ci
4967db96d56Sopenharmony_ci        * If called after Python has finish initializing (after
4977db96d56Sopenharmony_ci          :c:func:`Py_InitializeFromConfig` has been called) the allocator
4987db96d56Sopenharmony_ci          **must** wrap the existing allocator. Substituting the current
4997db96d56Sopenharmony_ci          allocator for some other arbitrary one is **not supported**.
5007db96d56Sopenharmony_ci
5017db96d56Sopenharmony_ci
5027db96d56Sopenharmony_ci
5037db96d56Sopenharmony_ci.. c:function:: void PyMem_SetupDebugHooks(void)
5047db96d56Sopenharmony_ci
5057db96d56Sopenharmony_ci   Setup :ref:`debug hooks in the Python memory allocators <pymem-debug-hooks>`
5067db96d56Sopenharmony_ci   to detect memory errors.
5077db96d56Sopenharmony_ci
5087db96d56Sopenharmony_ci
5097db96d56Sopenharmony_ci.. _pymem-debug-hooks:
5107db96d56Sopenharmony_ci
5117db96d56Sopenharmony_ciDebug hooks on the Python memory allocators
5127db96d56Sopenharmony_ci===========================================
5137db96d56Sopenharmony_ci
5147db96d56Sopenharmony_ciWhen :ref:`Python is built in debug mode <debug-build>`, the
5157db96d56Sopenharmony_ci:c:func:`PyMem_SetupDebugHooks` function is called at the :ref:`Python
5167db96d56Sopenharmony_cipreinitialization <c-preinit>` to setup debug hooks on Python memory allocators
5177db96d56Sopenharmony_cito detect memory errors.
5187db96d56Sopenharmony_ci
5197db96d56Sopenharmony_ciThe :envvar:`PYTHONMALLOC` environment variable can be used to install debug
5207db96d56Sopenharmony_cihooks on a Python compiled in release mode (ex: ``PYTHONMALLOC=debug``).
5217db96d56Sopenharmony_ci
5227db96d56Sopenharmony_ciThe :c:func:`PyMem_SetupDebugHooks` function can be used to set debug hooks
5237db96d56Sopenharmony_ciafter calling :c:func:`PyMem_SetAllocator`.
5247db96d56Sopenharmony_ci
5257db96d56Sopenharmony_ciThese debug hooks fill dynamically allocated memory blocks with special,
5267db96d56Sopenharmony_cirecognizable bit patterns. Newly allocated memory is filled with the byte
5277db96d56Sopenharmony_ci``0xCD`` (``PYMEM_CLEANBYTE``), freed memory is filled with the byte ``0xDD``
5287db96d56Sopenharmony_ci(``PYMEM_DEADBYTE``). Memory blocks are surrounded by "forbidden bytes"
5297db96d56Sopenharmony_cifilled with the byte ``0xFD`` (``PYMEM_FORBIDDENBYTE``). Strings of these bytes
5307db96d56Sopenharmony_ciare unlikely to be valid addresses, floats, or ASCII strings.
5317db96d56Sopenharmony_ci
5327db96d56Sopenharmony_ciRuntime checks:
5337db96d56Sopenharmony_ci
5347db96d56Sopenharmony_ci- Detect API violations. For example, detect if :c:func:`PyObject_Free` is
5357db96d56Sopenharmony_ci  called on a memory block allocated by :c:func:`PyMem_Malloc`.
5367db96d56Sopenharmony_ci- Detect write before the start of the buffer (buffer underflow).
5377db96d56Sopenharmony_ci- Detect write after the end of the buffer (buffer overflow).
5387db96d56Sopenharmony_ci- Check that the :term:`GIL <global interpreter lock>` is held when
5397db96d56Sopenharmony_ci  allocator functions of :c:data:`PYMEM_DOMAIN_OBJ` (ex:
5407db96d56Sopenharmony_ci  :c:func:`PyObject_Malloc`) and :c:data:`PYMEM_DOMAIN_MEM` (ex:
5417db96d56Sopenharmony_ci  :c:func:`PyMem_Malloc`) domains are called.
5427db96d56Sopenharmony_ci
5437db96d56Sopenharmony_ciOn error, the debug hooks use the :mod:`tracemalloc` module to get the
5447db96d56Sopenharmony_citraceback where a memory block was allocated. The traceback is only displayed
5457db96d56Sopenharmony_ciif :mod:`tracemalloc` is tracing Python memory allocations and the memory block
5467db96d56Sopenharmony_ciwas traced.
5477db96d56Sopenharmony_ci
5487db96d56Sopenharmony_ciLet *S* = ``sizeof(size_t)``. ``2*S`` bytes are added at each end of each block
5497db96d56Sopenharmony_ciof *N* bytes requested.  The memory layout is like so, where p represents the
5507db96d56Sopenharmony_ciaddress returned by a malloc-like or realloc-like function (``p[i:j]`` means
5517db96d56Sopenharmony_cithe slice of bytes from ``*(p+i)`` inclusive up to ``*(p+j)`` exclusive; note
5527db96d56Sopenharmony_cithat the treatment of negative indices differs from a Python slice):
5537db96d56Sopenharmony_ci
5547db96d56Sopenharmony_ci``p[-2*S:-S]``
5557db96d56Sopenharmony_ci    Number of bytes originally asked for.  This is a size_t, big-endian (easier
5567db96d56Sopenharmony_ci    to read in a memory dump).
5577db96d56Sopenharmony_ci``p[-S]``
5587db96d56Sopenharmony_ci    API identifier (ASCII character):
5597db96d56Sopenharmony_ci
5607db96d56Sopenharmony_ci    * ``'r'`` for :c:data:`PYMEM_DOMAIN_RAW`.
5617db96d56Sopenharmony_ci    * ``'m'`` for :c:data:`PYMEM_DOMAIN_MEM`.
5627db96d56Sopenharmony_ci    * ``'o'`` for :c:data:`PYMEM_DOMAIN_OBJ`.
5637db96d56Sopenharmony_ci
5647db96d56Sopenharmony_ci``p[-S+1:0]``
5657db96d56Sopenharmony_ci    Copies of PYMEM_FORBIDDENBYTE.  Used to catch under- writes and reads.
5667db96d56Sopenharmony_ci
5677db96d56Sopenharmony_ci``p[0:N]``
5687db96d56Sopenharmony_ci    The requested memory, filled with copies of PYMEM_CLEANBYTE, used to catch
5697db96d56Sopenharmony_ci    reference to uninitialized memory.  When a realloc-like function is called
5707db96d56Sopenharmony_ci    requesting a larger memory block, the new excess bytes are also filled with
5717db96d56Sopenharmony_ci    PYMEM_CLEANBYTE.  When a free-like function is called, these are
5727db96d56Sopenharmony_ci    overwritten with PYMEM_DEADBYTE, to catch reference to freed memory.  When
5737db96d56Sopenharmony_ci    a realloc- like function is called requesting a smaller memory block, the
5747db96d56Sopenharmony_ci    excess old bytes are also filled with PYMEM_DEADBYTE.
5757db96d56Sopenharmony_ci
5767db96d56Sopenharmony_ci``p[N:N+S]``
5777db96d56Sopenharmony_ci    Copies of PYMEM_FORBIDDENBYTE.  Used to catch over- writes and reads.
5787db96d56Sopenharmony_ci
5797db96d56Sopenharmony_ci``p[N+S:N+2*S]``
5807db96d56Sopenharmony_ci    Only used if the ``PYMEM_DEBUG_SERIALNO`` macro is defined (not defined by
5817db96d56Sopenharmony_ci    default).
5827db96d56Sopenharmony_ci
5837db96d56Sopenharmony_ci    A serial number, incremented by 1 on each call to a malloc-like or
5847db96d56Sopenharmony_ci    realloc-like function.  Big-endian ``size_t``.  If "bad memory" is detected
5857db96d56Sopenharmony_ci    later, the serial number gives an excellent way to set a breakpoint on the
5867db96d56Sopenharmony_ci    next run, to capture the instant at which this block was passed out.  The
5877db96d56Sopenharmony_ci    static function bumpserialno() in obmalloc.c is the only place the serial
5887db96d56Sopenharmony_ci    number is incremented, and exists so you can set such a breakpoint easily.
5897db96d56Sopenharmony_ci
5907db96d56Sopenharmony_ciA realloc-like or free-like function first checks that the PYMEM_FORBIDDENBYTE
5917db96d56Sopenharmony_cibytes at each end are intact.  If they've been altered, diagnostic output is
5927db96d56Sopenharmony_ciwritten to stderr, and the program is aborted via Py_FatalError().  The other
5937db96d56Sopenharmony_cimain failure mode is provoking a memory error when a program reads up one of
5947db96d56Sopenharmony_cithe special bit patterns and tries to use it as an address.  If you get in a
5957db96d56Sopenharmony_cidebugger then and look at the object, you're likely to see that it's entirely
5967db96d56Sopenharmony_cifilled with PYMEM_DEADBYTE (meaning freed memory is getting used) or
5977db96d56Sopenharmony_ciPYMEM_CLEANBYTE (meaning uninitialized memory is getting used).
5987db96d56Sopenharmony_ci
5997db96d56Sopenharmony_ci.. versionchanged:: 3.6
6007db96d56Sopenharmony_ci   The :c:func:`PyMem_SetupDebugHooks` function now also works on Python
6017db96d56Sopenharmony_ci   compiled in release mode.  On error, the debug hooks now use
6027db96d56Sopenharmony_ci   :mod:`tracemalloc` to get the traceback where a memory block was allocated.
6037db96d56Sopenharmony_ci   The debug hooks now also check if the GIL is held when functions of
6047db96d56Sopenharmony_ci   :c:data:`PYMEM_DOMAIN_OBJ` and :c:data:`PYMEM_DOMAIN_MEM` domains are
6057db96d56Sopenharmony_ci   called.
6067db96d56Sopenharmony_ci
6077db96d56Sopenharmony_ci.. versionchanged:: 3.8
6087db96d56Sopenharmony_ci   Byte patterns ``0xCB`` (``PYMEM_CLEANBYTE``), ``0xDB`` (``PYMEM_DEADBYTE``)
6097db96d56Sopenharmony_ci   and ``0xFB`` (``PYMEM_FORBIDDENBYTE``) have been replaced with ``0xCD``,
6107db96d56Sopenharmony_ci   ``0xDD`` and ``0xFD`` to use the same values than Windows CRT debug
6117db96d56Sopenharmony_ci   ``malloc()`` and ``free()``.
6127db96d56Sopenharmony_ci
6137db96d56Sopenharmony_ci
6147db96d56Sopenharmony_ci.. _pymalloc:
6157db96d56Sopenharmony_ci
6167db96d56Sopenharmony_ciThe pymalloc allocator
6177db96d56Sopenharmony_ci======================
6187db96d56Sopenharmony_ci
6197db96d56Sopenharmony_ciPython has a *pymalloc* allocator optimized for small objects (smaller or equal
6207db96d56Sopenharmony_cito 512 bytes) with a short lifetime. It uses memory mappings called "arenas"
6217db96d56Sopenharmony_ciwith a fixed size of 256 KiB. It falls back to :c:func:`PyMem_RawMalloc` and
6227db96d56Sopenharmony_ci:c:func:`PyMem_RawRealloc` for allocations larger than 512 bytes.
6237db96d56Sopenharmony_ci
6247db96d56Sopenharmony_ci*pymalloc* is the :ref:`default allocator <default-memory-allocators>` of the
6257db96d56Sopenharmony_ci:c:data:`PYMEM_DOMAIN_MEM` (ex: :c:func:`PyMem_Malloc`) and
6267db96d56Sopenharmony_ci:c:data:`PYMEM_DOMAIN_OBJ` (ex: :c:func:`PyObject_Malloc`) domains.
6277db96d56Sopenharmony_ci
6287db96d56Sopenharmony_ciThe arena allocator uses the following functions:
6297db96d56Sopenharmony_ci
6307db96d56Sopenharmony_ci* :c:func:`VirtualAlloc` and :c:func:`VirtualFree` on Windows,
6317db96d56Sopenharmony_ci* :c:func:`mmap` and :c:func:`munmap` if available,
6327db96d56Sopenharmony_ci* :c:func:`malloc` and :c:func:`free` otherwise.
6337db96d56Sopenharmony_ci
6347db96d56Sopenharmony_ciThis allocator is disabled if Python is configured with the
6357db96d56Sopenharmony_ci:option:`--without-pymalloc` option. It can also be disabled at runtime using
6367db96d56Sopenharmony_cithe :envvar:`PYTHONMALLOC` environment variable (ex: ``PYTHONMALLOC=malloc``).
6377db96d56Sopenharmony_ci
6387db96d56Sopenharmony_ciCustomize pymalloc Arena Allocator
6397db96d56Sopenharmony_ci----------------------------------
6407db96d56Sopenharmony_ci
6417db96d56Sopenharmony_ci.. versionadded:: 3.4
6427db96d56Sopenharmony_ci
6437db96d56Sopenharmony_ci.. c:type:: PyObjectArenaAllocator
6447db96d56Sopenharmony_ci
6457db96d56Sopenharmony_ci   Structure used to describe an arena allocator. The structure has
6467db96d56Sopenharmony_ci   three fields:
6477db96d56Sopenharmony_ci
6487db96d56Sopenharmony_ci   +--------------------------------------------------+---------------------------------------+
6497db96d56Sopenharmony_ci   | Field                                            | Meaning                               |
6507db96d56Sopenharmony_ci   +==================================================+=======================================+
6517db96d56Sopenharmony_ci   | ``void *ctx``                                    | user context passed as first argument |
6527db96d56Sopenharmony_ci   +--------------------------------------------------+---------------------------------------+
6537db96d56Sopenharmony_ci   | ``void* alloc(void *ctx, size_t size)``          | allocate an arena of size bytes       |
6547db96d56Sopenharmony_ci   +--------------------------------------------------+---------------------------------------+
6557db96d56Sopenharmony_ci   | ``void free(void *ctx, void *ptr, size_t size)`` | free an arena                         |
6567db96d56Sopenharmony_ci   +--------------------------------------------------+---------------------------------------+
6577db96d56Sopenharmony_ci
6587db96d56Sopenharmony_ci.. c:function:: void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
6597db96d56Sopenharmony_ci
6607db96d56Sopenharmony_ci   Get the arena allocator.
6617db96d56Sopenharmony_ci
6627db96d56Sopenharmony_ci.. c:function:: void PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
6637db96d56Sopenharmony_ci
6647db96d56Sopenharmony_ci   Set the arena allocator.
6657db96d56Sopenharmony_ci
6667db96d56Sopenharmony_ci
6677db96d56Sopenharmony_citracemalloc C API
6687db96d56Sopenharmony_ci=================
6697db96d56Sopenharmony_ci
6707db96d56Sopenharmony_ci.. versionadded:: 3.7
6717db96d56Sopenharmony_ci
6727db96d56Sopenharmony_ci.. c:function:: int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size)
6737db96d56Sopenharmony_ci
6747db96d56Sopenharmony_ci   Track an allocated memory block in the :mod:`tracemalloc` module.
6757db96d56Sopenharmony_ci
6767db96d56Sopenharmony_ci   Return ``0`` on success, return ``-1`` on error (failed to allocate memory to
6777db96d56Sopenharmony_ci   store the trace). Return ``-2`` if tracemalloc is disabled.
6787db96d56Sopenharmony_ci
6797db96d56Sopenharmony_ci   If memory block is already tracked, update the existing trace.
6807db96d56Sopenharmony_ci
6817db96d56Sopenharmony_ci.. c:function:: int PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr)
6827db96d56Sopenharmony_ci
6837db96d56Sopenharmony_ci   Untrack an allocated memory block in the :mod:`tracemalloc` module.
6847db96d56Sopenharmony_ci   Do nothing if the block was not tracked.
6857db96d56Sopenharmony_ci
6867db96d56Sopenharmony_ci   Return ``-2`` if tracemalloc is disabled, otherwise return ``0``.
6877db96d56Sopenharmony_ci
6887db96d56Sopenharmony_ci
6897db96d56Sopenharmony_ci.. _memoryexamples:
6907db96d56Sopenharmony_ci
6917db96d56Sopenharmony_ciExamples
6927db96d56Sopenharmony_ci========
6937db96d56Sopenharmony_ci
6947db96d56Sopenharmony_ciHere is the example from section :ref:`memoryoverview`, rewritten so that the
6957db96d56Sopenharmony_ciI/O buffer is allocated from the Python heap by using the first function set::
6967db96d56Sopenharmony_ci
6977db96d56Sopenharmony_ci   PyObject *res;
6987db96d56Sopenharmony_ci   char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
6997db96d56Sopenharmony_ci
7007db96d56Sopenharmony_ci   if (buf == NULL)
7017db96d56Sopenharmony_ci       return PyErr_NoMemory();
7027db96d56Sopenharmony_ci   /* ...Do some I/O operation involving buf... */
7037db96d56Sopenharmony_ci   res = PyBytes_FromString(buf);
7047db96d56Sopenharmony_ci   PyMem_Free(buf); /* allocated with PyMem_Malloc */
7057db96d56Sopenharmony_ci   return res;
7067db96d56Sopenharmony_ci
7077db96d56Sopenharmony_ciThe same code using the type-oriented function set::
7087db96d56Sopenharmony_ci
7097db96d56Sopenharmony_ci   PyObject *res;
7107db96d56Sopenharmony_ci   char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
7117db96d56Sopenharmony_ci
7127db96d56Sopenharmony_ci   if (buf == NULL)
7137db96d56Sopenharmony_ci       return PyErr_NoMemory();
7147db96d56Sopenharmony_ci   /* ...Do some I/O operation involving buf... */
7157db96d56Sopenharmony_ci   res = PyBytes_FromString(buf);
7167db96d56Sopenharmony_ci   PyMem_Del(buf); /* allocated with PyMem_New */
7177db96d56Sopenharmony_ci   return res;
7187db96d56Sopenharmony_ci
7197db96d56Sopenharmony_ciNote that in the two examples above, the buffer is always manipulated via
7207db96d56Sopenharmony_cifunctions belonging to the same set. Indeed, it is required to use the same
7217db96d56Sopenharmony_cimemory API family for a given memory block, so that the risk of mixing different
7227db96d56Sopenharmony_ciallocators is reduced to a minimum. The following code sequence contains two
7237db96d56Sopenharmony_cierrors, one of which is labeled as *fatal* because it mixes two different
7247db96d56Sopenharmony_ciallocators operating on different heaps. ::
7257db96d56Sopenharmony_ci
7267db96d56Sopenharmony_ci   char *buf1 = PyMem_New(char, BUFSIZ);
7277db96d56Sopenharmony_ci   char *buf2 = (char *) malloc(BUFSIZ);
7287db96d56Sopenharmony_ci   char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
7297db96d56Sopenharmony_ci   ...
7307db96d56Sopenharmony_ci   PyMem_Del(buf3);  /* Wrong -- should be PyMem_Free() */
7317db96d56Sopenharmony_ci   free(buf2);       /* Right -- allocated via malloc() */
7327db96d56Sopenharmony_ci   free(buf1);       /* Fatal -- should be PyMem_Del()  */
7337db96d56Sopenharmony_ci
7347db96d56Sopenharmony_ciIn addition to the functions aimed at handling raw memory blocks from the Python
7357db96d56Sopenharmony_ciheap, objects in Python are allocated and released with :c:func:`PyObject_New`,
7367db96d56Sopenharmony_ci:c:func:`PyObject_NewVar` and :c:func:`PyObject_Del`.
7377db96d56Sopenharmony_ci
7387db96d56Sopenharmony_ciThese will be explained in the next chapter on defining and implementing new
7397db96d56Sopenharmony_ciobject types in C.
740