1.. highlight:: c
2
3
4.. _memory:
5
6*****************
7Memory Management
8*****************
9
10.. sectionauthor:: Vladimir Marangozov <[email protected]>
11
12
13
14.. _memoryoverview:
15
16Overview
17========
18
19Memory management in Python involves a private heap containing all Python
20objects and data structures. The management of this private heap is ensured
21internally by the *Python memory manager*.  The Python memory manager has
22different components which deal with various dynamic storage management aspects,
23like sharing, segmentation, preallocation or caching.
24
25At the lowest level, a raw memory allocator ensures that there is enough room in
26the private heap for storing all Python-related data by interacting with the
27memory manager of the operating system. On top of the raw memory allocator,
28several object-specific allocators operate on the same heap and implement
29distinct memory management policies adapted to the peculiarities of every object
30type. For example, integer objects are managed differently within the heap than
31strings, tuples or dictionaries because integers imply different storage
32requirements and speed/space tradeoffs. The Python memory manager thus delegates
33some of the work to the object-specific allocators, but ensures that the latter
34operate within the bounds of the private heap.
35
36It is important to understand that the management of the Python heap is
37performed by the interpreter itself and that the user has no control over it,
38even if they regularly manipulate object pointers to memory blocks inside that
39heap.  The allocation of heap space for Python objects and other internal
40buffers is performed on demand by the Python memory manager through the Python/C
41API functions listed in this document.
42
43.. index::
44   single: malloc()
45   single: calloc()
46   single: realloc()
47   single: free()
48
49To avoid memory corruption, extension writers should never try to operate on
50Python objects with the functions exported by the C library: :c:func:`malloc`,
51:c:func:`calloc`, :c:func:`realloc` and :c:func:`free`.  This will result in  mixed
52calls between the C allocator and the Python memory manager with fatal
53consequences, because they implement different algorithms and operate on
54different heaps.  However, one may safely allocate and release memory blocks
55with the C library allocator for individual purposes, as shown in the following
56example::
57
58   PyObject *res;
59   char *buf = (char *) malloc(BUFSIZ); /* for I/O */
60
61   if (buf == NULL)
62       return PyErr_NoMemory();
63   ...Do some I/O operation involving buf...
64   res = PyBytes_FromString(buf);
65   free(buf); /* malloc'ed */
66   return res;
67
68In this example, the memory request for the I/O buffer is handled by the C
69library allocator. The Python memory manager is involved only in the allocation
70of the bytes object returned as a result.
71
72In most situations, however, it is recommended to allocate memory from the
73Python heap specifically because the latter is under control of the Python
74memory manager. For example, this is required when the interpreter is extended
75with new object types written in C. Another reason for using the Python heap is
76the desire to *inform* the Python memory manager about the memory needs of the
77extension module. Even when the requested memory is used exclusively for
78internal, highly specific purposes, delegating all memory requests to the Python
79memory manager causes the interpreter to have a more accurate image of its
80memory footprint as a whole. Consequently, under certain circumstances, the
81Python memory manager may or may not trigger appropriate actions, like garbage
82collection, memory compaction or other preventive procedures. Note that by using
83the C library allocator as shown in the previous example, the allocated memory
84for the I/O buffer escapes completely the Python memory manager.
85
86.. seealso::
87
88   The :envvar:`PYTHONMALLOC` environment variable can be used to configure
89   the memory allocators used by Python.
90
91   The :envvar:`PYTHONMALLOCSTATS` environment variable can be used to print
92   statistics of the :ref:`pymalloc memory allocator <pymalloc>` every time a
93   new pymalloc object arena is created, and on shutdown.
94
95Allocator Domains
96=================
97
98.. _allocator-domains:
99
100All allocating functions belong to one of three different "domains" (see also
101:c:type:`PyMemAllocatorDomain`). These domains represent different allocation
102strategies and are optimized for different purposes. The specific details on
103how every domain allocates memory or what internal functions each domain calls
104is considered an implementation detail, but for debugging purposes a simplified
105table can be found at :ref:`here <default-memory-allocators>`. There is no hard
106requirement to use the memory returned by the allocation functions belonging to
107a given domain for only the purposes hinted by that domain (although this is the
108recommended practice). For example, one could use the memory returned by
109:c:func:`PyMem_RawMalloc` for allocating Python objects or the memory returned
110by :c:func:`PyObject_Malloc` for allocating memory for buffers.
111
112The three allocation domains are:
113
114* Raw domain: intended for allocating memory for general-purpose memory
115  buffers where the allocation *must* go to the system allocator or where the
116  allocator can operate without the :term:`GIL`. The memory is requested directly
117  to the system.
118
119* "Mem" domain: intended for allocating memory for Python buffers and
120  general-purpose memory buffers where the allocation must be performed with
121  the :term:`GIL` held. The memory is taken from the Python private heap.
122
123* Object domain: intended for allocating memory belonging to Python objects. The
124  memory is taken from the Python private heap.
125
126When freeing memory previously allocated by the allocating functions belonging to a
127given domain,the matching specific deallocating functions must be used. For example,
128:c:func:`PyMem_Free` must be used to free memory allocated using :c:func:`PyMem_Malloc`.
129
130Raw Memory Interface
131====================
132
133The following function sets are wrappers to the system allocator. These
134functions are thread-safe, the :term:`GIL <global interpreter lock>` does not
135need to be held.
136
137The :ref:`default raw memory allocator <default-memory-allocators>` uses
138the following functions: :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc`
139and :c:func:`free`; call ``malloc(1)`` (or ``calloc(1, 1)``) when requesting
140zero bytes.
141
142.. versionadded:: 3.4
143
144.. c:function:: void* PyMem_RawMalloc(size_t n)
145
146   Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the
147   allocated memory, or ``NULL`` if the request fails.
148
149   Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as
150   if ``PyMem_RawMalloc(1)`` had been called instead. The memory will not have
151   been initialized in any way.
152
153
154.. c:function:: void* PyMem_RawCalloc(size_t nelem, size_t elsize)
155
156   Allocates *nelem* elements each whose size in bytes is *elsize* and returns
157   a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the
158   request fails. The memory is initialized to zeros.
159
160   Requesting zero elements or elements of size zero bytes returns a distinct
161   non-``NULL`` pointer if possible, as if ``PyMem_RawCalloc(1, 1)`` had been
162   called instead.
163
164   .. versionadded:: 3.5
165
166
167.. c:function:: void* PyMem_RawRealloc(void *p, size_t n)
168
169   Resizes the memory block pointed to by *p* to *n* bytes. The contents will
170   be unchanged to the minimum of the old and the new sizes.
171
172   If *p* is ``NULL``, the call is equivalent to ``PyMem_RawMalloc(n)``; else if
173   *n* is equal to zero, the memory block is resized but is not freed, and the
174   returned pointer is non-``NULL``.
175
176   Unless *p* is ``NULL``, it must have been returned by a previous call to
177   :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc` or
178   :c:func:`PyMem_RawCalloc`.
179
180   If the request fails, :c:func:`PyMem_RawRealloc` returns ``NULL`` and *p*
181   remains a valid pointer to the previous memory area.
182
183
184.. c:function:: void PyMem_RawFree(void *p)
185
186   Frees the memory block pointed to by *p*, which must have been returned by a
187   previous call to :c:func:`PyMem_RawMalloc`, :c:func:`PyMem_RawRealloc` or
188   :c:func:`PyMem_RawCalloc`.  Otherwise, or if ``PyMem_RawFree(p)`` has been
189   called before, undefined behavior occurs.
190
191   If *p* is ``NULL``, no operation is performed.
192
193
194.. _memoryinterface:
195
196Memory Interface
197================
198
199The following function sets, modeled after the ANSI C standard, but specifying
200behavior when requesting zero bytes, are available for allocating and releasing
201memory from the Python heap.
202
203The :ref:`default memory allocator <default-memory-allocators>` uses the
204:ref:`pymalloc memory allocator <pymalloc>`.
205
206.. warning::
207
208   The :term:`GIL <global interpreter lock>` must be held when using these
209   functions.
210
211.. versionchanged:: 3.6
212
213   The default allocator is now pymalloc instead of system :c:func:`malloc`.
214
215.. c:function:: void* PyMem_Malloc(size_t n)
216
217   Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the
218   allocated memory, or ``NULL`` if the request fails.
219
220   Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as
221   if ``PyMem_Malloc(1)`` had been called instead. The memory will not have
222   been initialized in any way.
223
224
225.. c:function:: void* PyMem_Calloc(size_t nelem, size_t elsize)
226
227   Allocates *nelem* elements each whose size in bytes is *elsize* and returns
228   a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the
229   request fails. The memory is initialized to zeros.
230
231   Requesting zero elements or elements of size zero bytes returns a distinct
232   non-``NULL`` pointer if possible, as if ``PyMem_Calloc(1, 1)`` had been called
233   instead.
234
235   .. versionadded:: 3.5
236
237
238.. c:function:: void* PyMem_Realloc(void *p, size_t n)
239
240   Resizes the memory block pointed to by *p* to *n* bytes. The contents will be
241   unchanged to the minimum of the old and the new sizes.
242
243   If *p* is ``NULL``, the call is equivalent to ``PyMem_Malloc(n)``; else if *n*
244   is equal to zero, the memory block is resized but is not freed, and the
245   returned pointer is non-``NULL``.
246
247   Unless *p* is ``NULL``, it must have been returned by a previous call to
248   :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or :c:func:`PyMem_Calloc`.
249
250   If the request fails, :c:func:`PyMem_Realloc` returns ``NULL`` and *p* remains
251   a valid pointer to the previous memory area.
252
253
254.. c:function:: void PyMem_Free(void *p)
255
256   Frees the memory block pointed to by *p*, which must have been returned by a
257   previous call to :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc` or
258   :c:func:`PyMem_Calloc`.  Otherwise, or if ``PyMem_Free(p)`` has been called
259   before, undefined behavior occurs.
260
261   If *p* is ``NULL``, no operation is performed.
262
263The following type-oriented macros are provided for convenience.  Note  that
264*TYPE* refers to any C type.
265
266
267.. c:function:: TYPE* PyMem_New(TYPE, size_t n)
268
269   Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of
270   memory.  Returns a pointer cast to :c:expr:`TYPE*`.  The memory will not have
271   been initialized in any way.
272
273
274.. c:function:: TYPE* PyMem_Resize(void *p, TYPE, size_t n)
275
276   Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n *
277   sizeof(TYPE))`` bytes.  Returns a pointer cast to :c:expr:`TYPE*`. On return,
278   *p* will be a pointer to the new memory area, or ``NULL`` in the event of
279   failure.
280
281   This is a C preprocessor macro; *p* is always reassigned.  Save the original
282   value of *p* to avoid losing memory when handling errors.
283
284
285.. c:function:: void PyMem_Del(void *p)
286
287   Same as :c:func:`PyMem_Free`.
288
289In addition, the following macro sets are provided for calling the Python memory
290allocator directly, without involving the C API functions listed above. However,
291note that their use does not preserve binary compatibility across Python
292versions and is therefore deprecated in extension modules.
293
294* ``PyMem_MALLOC(size)``
295* ``PyMem_NEW(type, size)``
296* ``PyMem_REALLOC(ptr, size)``
297* ``PyMem_RESIZE(ptr, type, size)``
298* ``PyMem_FREE(ptr)``
299* ``PyMem_DEL(ptr)``
300
301
302Object allocators
303=================
304
305The following function sets, modeled after the ANSI C standard, but specifying
306behavior when requesting zero bytes, are available for allocating and releasing
307memory from the Python heap.
308
309.. note::
310    There is no guarantee that the memory returned by these allocators can be
311    successfully cast to a Python object when intercepting the allocating
312    functions in this domain by the methods described in
313    the :ref:`Customize Memory Allocators <customize-memory-allocators>` section.
314
315The :ref:`default object allocator <default-memory-allocators>` uses the
316:ref:`pymalloc memory allocator <pymalloc>`.
317
318.. warning::
319
320   The :term:`GIL <global interpreter lock>` must be held when using these
321   functions.
322
323.. c:function:: void* PyObject_Malloc(size_t n)
324
325   Allocates *n* bytes and returns a pointer of type :c:expr:`void*` to the
326   allocated memory, or ``NULL`` if the request fails.
327
328   Requesting zero bytes returns a distinct non-``NULL`` pointer if possible, as
329   if ``PyObject_Malloc(1)`` had been called instead. The memory will not have
330   been initialized in any way.
331
332
333.. c:function:: void* PyObject_Calloc(size_t nelem, size_t elsize)
334
335   Allocates *nelem* elements each whose size in bytes is *elsize* and returns
336   a pointer of type :c:expr:`void*` to the allocated memory, or ``NULL`` if the
337   request fails. The memory is initialized to zeros.
338
339   Requesting zero elements or elements of size zero bytes returns a distinct
340   non-``NULL`` pointer if possible, as if ``PyObject_Calloc(1, 1)`` had been called
341   instead.
342
343   .. versionadded:: 3.5
344
345
346.. c:function:: void* PyObject_Realloc(void *p, size_t n)
347
348   Resizes the memory block pointed to by *p* to *n* bytes. The contents will be
349   unchanged to the minimum of the old and the new sizes.
350
351   If *p* is ``NULL``, the call is equivalent to ``PyObject_Malloc(n)``; else if *n*
352   is equal to zero, the memory block is resized but is not freed, and the
353   returned pointer is non-``NULL``.
354
355   Unless *p* is ``NULL``, it must have been returned by a previous call to
356   :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or :c:func:`PyObject_Calloc`.
357
358   If the request fails, :c:func:`PyObject_Realloc` returns ``NULL`` and *p* remains
359   a valid pointer to the previous memory area.
360
361
362.. c:function:: void PyObject_Free(void *p)
363
364   Frees the memory block pointed to by *p*, which must have been returned by a
365   previous call to :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or
366   :c:func:`PyObject_Calloc`.  Otherwise, or if ``PyObject_Free(p)`` has been called
367   before, undefined behavior occurs.
368
369   If *p* is ``NULL``, no operation is performed.
370
371
372.. _default-memory-allocators:
373
374Default Memory Allocators
375=========================
376
377Default memory allocators:
378
379===============================  ====================  ==================  =====================  ====================
380Configuration                    Name                  PyMem_RawMalloc     PyMem_Malloc           PyObject_Malloc
381===============================  ====================  ==================  =====================  ====================
382Release build                    ``"pymalloc"``        ``malloc``          ``pymalloc``           ``pymalloc``
383Debug build                      ``"pymalloc_debug"``  ``malloc`` + debug  ``pymalloc`` + debug   ``pymalloc`` + debug
384Release build, without pymalloc  ``"malloc"``          ``malloc``          ``malloc``             ``malloc``
385Debug build, without pymalloc    ``"malloc_debug"``    ``malloc`` + debug  ``malloc`` + debug     ``malloc`` + debug
386===============================  ====================  ==================  =====================  ====================
387
388Legend:
389
390* Name: value for :envvar:`PYTHONMALLOC` environment variable.
391* ``malloc``: system allocators from the standard C library, C functions:
392  :c:func:`malloc`, :c:func:`calloc`, :c:func:`realloc` and :c:func:`free`.
393* ``pymalloc``: :ref:`pymalloc memory allocator <pymalloc>`.
394* "+ debug": with :ref:`debug hooks on the Python memory allocators
395  <pymem-debug-hooks>`.
396* "Debug build": :ref:`Python build in debug mode <debug-build>`.
397
398.. _customize-memory-allocators:
399
400Customize Memory Allocators
401===========================
402
403.. versionadded:: 3.4
404
405.. c:type:: PyMemAllocatorEx
406
407   Structure used to describe a memory block allocator. The structure has
408   the following fields:
409
410   +----------------------------------------------------------+---------------------------------------+
411   | Field                                                    | Meaning                               |
412   +==========================================================+=======================================+
413   | ``void *ctx``                                            | user context passed as first argument |
414   +----------------------------------------------------------+---------------------------------------+
415   | ``void* malloc(void *ctx, size_t size)``                 | allocate a memory block               |
416   +----------------------------------------------------------+---------------------------------------+
417   | ``void* calloc(void *ctx, size_t nelem, size_t elsize)`` | allocate a memory block initialized   |
418   |                                                          | with zeros                            |
419   +----------------------------------------------------------+---------------------------------------+
420   | ``void* realloc(void *ctx, void *ptr, size_t new_size)`` | allocate or resize a memory block     |
421   +----------------------------------------------------------+---------------------------------------+
422   | ``void free(void *ctx, void *ptr)``                      | free a memory block                   |
423   +----------------------------------------------------------+---------------------------------------+
424
425   .. versionchanged:: 3.5
426      The :c:type:`PyMemAllocator` structure was renamed to
427      :c:type:`PyMemAllocatorEx` and a new ``calloc`` field was added.
428
429
430.. c:type:: PyMemAllocatorDomain
431
432   Enum used to identify an allocator domain. Domains:
433
434   .. c:macro:: PYMEM_DOMAIN_RAW
435
436      Functions:
437
438      * :c:func:`PyMem_RawMalloc`
439      * :c:func:`PyMem_RawRealloc`
440      * :c:func:`PyMem_RawCalloc`
441      * :c:func:`PyMem_RawFree`
442
443   .. c:macro:: PYMEM_DOMAIN_MEM
444
445      Functions:
446
447      * :c:func:`PyMem_Malloc`,
448      * :c:func:`PyMem_Realloc`
449      * :c:func:`PyMem_Calloc`
450      * :c:func:`PyMem_Free`
451
452   .. c:macro:: PYMEM_DOMAIN_OBJ
453
454      Functions:
455
456      * :c:func:`PyObject_Malloc`
457      * :c:func:`PyObject_Realloc`
458      * :c:func:`PyObject_Calloc`
459      * :c:func:`PyObject_Free`
460
461.. c:function:: void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
462
463   Get the memory block allocator of the specified domain.
464
465
466.. c:function:: void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)
467
468   Set the memory block allocator of the specified domain.
469
470   The new allocator must return a distinct non-``NULL`` pointer when requesting
471   zero bytes.
472
473   For the :c:data:`PYMEM_DOMAIN_RAW` domain, the allocator must be
474   thread-safe: the :term:`GIL <global interpreter lock>` is not held when the
475   allocator is called.
476
477   If the new allocator is not a hook (does not call the previous allocator),
478   the :c:func:`PyMem_SetupDebugHooks` function must be called to reinstall the
479   debug hooks on top on the new allocator.
480
481   See also :c:member:`PyPreConfig.allocator` and :ref:`Preinitialize Python
482   with PyPreConfig <c-preinit>`.
483
484   .. warning::
485
486       :c:func:`PyMem_SetAllocator` does have the following contract:
487
488        * It can be called after :c:func:`Py_PreInitialize` and before
489          :c:func:`Py_InitializeFromConfig` to install a custom memory
490          allocator. There are no restrictions over the installed allocator
491          other than the ones imposed by the domain (for instance, the Raw
492          Domain allows the allocator to be called without the GIL held). See
493          :ref:`the section on allocator domains <allocator-domains>` for more
494          information.
495
496        * If called after Python has finish initializing (after
497          :c:func:`Py_InitializeFromConfig` has been called) the allocator
498          **must** wrap the existing allocator. Substituting the current
499          allocator for some other arbitrary one is **not supported**.
500
501
502
503.. c:function:: void PyMem_SetupDebugHooks(void)
504
505   Setup :ref:`debug hooks in the Python memory allocators <pymem-debug-hooks>`
506   to detect memory errors.
507
508
509.. _pymem-debug-hooks:
510
511Debug hooks on the Python memory allocators
512===========================================
513
514When :ref:`Python is built in debug mode <debug-build>`, the
515:c:func:`PyMem_SetupDebugHooks` function is called at the :ref:`Python
516preinitialization <c-preinit>` to setup debug hooks on Python memory allocators
517to detect memory errors.
518
519The :envvar:`PYTHONMALLOC` environment variable can be used to install debug
520hooks on a Python compiled in release mode (ex: ``PYTHONMALLOC=debug``).
521
522The :c:func:`PyMem_SetupDebugHooks` function can be used to set debug hooks
523after calling :c:func:`PyMem_SetAllocator`.
524
525These debug hooks fill dynamically allocated memory blocks with special,
526recognizable bit patterns. Newly allocated memory is filled with the byte
527``0xCD`` (``PYMEM_CLEANBYTE``), freed memory is filled with the byte ``0xDD``
528(``PYMEM_DEADBYTE``). Memory blocks are surrounded by "forbidden bytes"
529filled with the byte ``0xFD`` (``PYMEM_FORBIDDENBYTE``). Strings of these bytes
530are unlikely to be valid addresses, floats, or ASCII strings.
531
532Runtime checks:
533
534- Detect API violations. For example, detect if :c:func:`PyObject_Free` is
535  called on a memory block allocated by :c:func:`PyMem_Malloc`.
536- Detect write before the start of the buffer (buffer underflow).
537- Detect write after the end of the buffer (buffer overflow).
538- Check that the :term:`GIL <global interpreter lock>` is held when
539  allocator functions of :c:data:`PYMEM_DOMAIN_OBJ` (ex:
540  :c:func:`PyObject_Malloc`) and :c:data:`PYMEM_DOMAIN_MEM` (ex:
541  :c:func:`PyMem_Malloc`) domains are called.
542
543On error, the debug hooks use the :mod:`tracemalloc` module to get the
544traceback where a memory block was allocated. The traceback is only displayed
545if :mod:`tracemalloc` is tracing Python memory allocations and the memory block
546was traced.
547
548Let *S* = ``sizeof(size_t)``. ``2*S`` bytes are added at each end of each block
549of *N* bytes requested.  The memory layout is like so, where p represents the
550address returned by a malloc-like or realloc-like function (``p[i:j]`` means
551the slice of bytes from ``*(p+i)`` inclusive up to ``*(p+j)`` exclusive; note
552that the treatment of negative indices differs from a Python slice):
553
554``p[-2*S:-S]``
555    Number of bytes originally asked for.  This is a size_t, big-endian (easier
556    to read in a memory dump).
557``p[-S]``
558    API identifier (ASCII character):
559
560    * ``'r'`` for :c:data:`PYMEM_DOMAIN_RAW`.
561    * ``'m'`` for :c:data:`PYMEM_DOMAIN_MEM`.
562    * ``'o'`` for :c:data:`PYMEM_DOMAIN_OBJ`.
563
564``p[-S+1:0]``
565    Copies of PYMEM_FORBIDDENBYTE.  Used to catch under- writes and reads.
566
567``p[0:N]``
568    The requested memory, filled with copies of PYMEM_CLEANBYTE, used to catch
569    reference to uninitialized memory.  When a realloc-like function is called
570    requesting a larger memory block, the new excess bytes are also filled with
571    PYMEM_CLEANBYTE.  When a free-like function is called, these are
572    overwritten with PYMEM_DEADBYTE, to catch reference to freed memory.  When
573    a realloc- like function is called requesting a smaller memory block, the
574    excess old bytes are also filled with PYMEM_DEADBYTE.
575
576``p[N:N+S]``
577    Copies of PYMEM_FORBIDDENBYTE.  Used to catch over- writes and reads.
578
579``p[N+S:N+2*S]``
580    Only used if the ``PYMEM_DEBUG_SERIALNO`` macro is defined (not defined by
581    default).
582
583    A serial number, incremented by 1 on each call to a malloc-like or
584    realloc-like function.  Big-endian ``size_t``.  If "bad memory" is detected
585    later, the serial number gives an excellent way to set a breakpoint on the
586    next run, to capture the instant at which this block was passed out.  The
587    static function bumpserialno() in obmalloc.c is the only place the serial
588    number is incremented, and exists so you can set such a breakpoint easily.
589
590A realloc-like or free-like function first checks that the PYMEM_FORBIDDENBYTE
591bytes at each end are intact.  If they've been altered, diagnostic output is
592written to stderr, and the program is aborted via Py_FatalError().  The other
593main failure mode is provoking a memory error when a program reads up one of
594the special bit patterns and tries to use it as an address.  If you get in a
595debugger then and look at the object, you're likely to see that it's entirely
596filled with PYMEM_DEADBYTE (meaning freed memory is getting used) or
597PYMEM_CLEANBYTE (meaning uninitialized memory is getting used).
598
599.. versionchanged:: 3.6
600   The :c:func:`PyMem_SetupDebugHooks` function now also works on Python
601   compiled in release mode.  On error, the debug hooks now use
602   :mod:`tracemalloc` to get the traceback where a memory block was allocated.
603   The debug hooks now also check if the GIL is held when functions of
604   :c:data:`PYMEM_DOMAIN_OBJ` and :c:data:`PYMEM_DOMAIN_MEM` domains are
605   called.
606
607.. versionchanged:: 3.8
608   Byte patterns ``0xCB`` (``PYMEM_CLEANBYTE``), ``0xDB`` (``PYMEM_DEADBYTE``)
609   and ``0xFB`` (``PYMEM_FORBIDDENBYTE``) have been replaced with ``0xCD``,
610   ``0xDD`` and ``0xFD`` to use the same values than Windows CRT debug
611   ``malloc()`` and ``free()``.
612
613
614.. _pymalloc:
615
616The pymalloc allocator
617======================
618
619Python has a *pymalloc* allocator optimized for small objects (smaller or equal
620to 512 bytes) with a short lifetime. It uses memory mappings called "arenas"
621with a fixed size of 256 KiB. It falls back to :c:func:`PyMem_RawMalloc` and
622:c:func:`PyMem_RawRealloc` for allocations larger than 512 bytes.
623
624*pymalloc* is the :ref:`default allocator <default-memory-allocators>` of the
625:c:data:`PYMEM_DOMAIN_MEM` (ex: :c:func:`PyMem_Malloc`) and
626:c:data:`PYMEM_DOMAIN_OBJ` (ex: :c:func:`PyObject_Malloc`) domains.
627
628The arena allocator uses the following functions:
629
630* :c:func:`VirtualAlloc` and :c:func:`VirtualFree` on Windows,
631* :c:func:`mmap` and :c:func:`munmap` if available,
632* :c:func:`malloc` and :c:func:`free` otherwise.
633
634This allocator is disabled if Python is configured with the
635:option:`--without-pymalloc` option. It can also be disabled at runtime using
636the :envvar:`PYTHONMALLOC` environment variable (ex: ``PYTHONMALLOC=malloc``).
637
638Customize pymalloc Arena Allocator
639----------------------------------
640
641.. versionadded:: 3.4
642
643.. c:type:: PyObjectArenaAllocator
644
645   Structure used to describe an arena allocator. The structure has
646   three fields:
647
648   +--------------------------------------------------+---------------------------------------+
649   | Field                                            | Meaning                               |
650   +==================================================+=======================================+
651   | ``void *ctx``                                    | user context passed as first argument |
652   +--------------------------------------------------+---------------------------------------+
653   | ``void* alloc(void *ctx, size_t size)``          | allocate an arena of size bytes       |
654   +--------------------------------------------------+---------------------------------------+
655   | ``void free(void *ctx, void *ptr, size_t size)`` | free an arena                         |
656   +--------------------------------------------------+---------------------------------------+
657
658.. c:function:: void PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)
659
660   Get the arena allocator.
661
662.. c:function:: void PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)
663
664   Set the arena allocator.
665
666
667tracemalloc C API
668=================
669
670.. versionadded:: 3.7
671
672.. c:function:: int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size)
673
674   Track an allocated memory block in the :mod:`tracemalloc` module.
675
676   Return ``0`` on success, return ``-1`` on error (failed to allocate memory to
677   store the trace). Return ``-2`` if tracemalloc is disabled.
678
679   If memory block is already tracked, update the existing trace.
680
681.. c:function:: int PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr)
682
683   Untrack an allocated memory block in the :mod:`tracemalloc` module.
684   Do nothing if the block was not tracked.
685
686   Return ``-2`` if tracemalloc is disabled, otherwise return ``0``.
687
688
689.. _memoryexamples:
690
691Examples
692========
693
694Here is the example from section :ref:`memoryoverview`, rewritten so that the
695I/O buffer is allocated from the Python heap by using the first function set::
696
697   PyObject *res;
698   char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
699
700   if (buf == NULL)
701       return PyErr_NoMemory();
702   /* ...Do some I/O operation involving buf... */
703   res = PyBytes_FromString(buf);
704   PyMem_Free(buf); /* allocated with PyMem_Malloc */
705   return res;
706
707The same code using the type-oriented function set::
708
709   PyObject *res;
710   char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
711
712   if (buf == NULL)
713       return PyErr_NoMemory();
714   /* ...Do some I/O operation involving buf... */
715   res = PyBytes_FromString(buf);
716   PyMem_Del(buf); /* allocated with PyMem_New */
717   return res;
718
719Note that in the two examples above, the buffer is always manipulated via
720functions belonging to the same set. Indeed, it is required to use the same
721memory API family for a given memory block, so that the risk of mixing different
722allocators is reduced to a minimum. The following code sequence contains two
723errors, one of which is labeled as *fatal* because it mixes two different
724allocators operating on different heaps. ::
725
726   char *buf1 = PyMem_New(char, BUFSIZ);
727   char *buf2 = (char *) malloc(BUFSIZ);
728   char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
729   ...
730   PyMem_Del(buf3);  /* Wrong -- should be PyMem_Free() */
731   free(buf2);       /* Right -- allocated via malloc() */
732   free(buf1);       /* Fatal -- should be PyMem_Del()  */
733
734In addition to the functions aimed at handling raw memory blocks from the Python
735heap, objects in Python are allocated and released with :c:func:`PyObject_New`,
736:c:func:`PyObject_NewVar` and :c:func:`PyObject_Del`.
737
738These will be explained in the next chapter on defining and implementing new
739object types in C.
740