Debian Codegraph @

Doc/c-api/memory.rst

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