You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

209 lines
8.4 KiB

  1. .. highlightlang:: c
  2. .. _memory:
  3. *****************
  4. Memory Management
  5. *****************
  6. .. sectionauthor:: Vladimir Marangozov <Vladimir.Marangozov@inrialpes.fr>
  7. .. _memoryoverview:
  8. Overview
  9. ========
  10. Memory management in Python involves a private heap containing all Python
  11. objects and data structures. The management of this private heap is ensured
  12. internally by the *Python memory manager*. The Python memory manager has
  13. different components which deal with various dynamic storage management aspects,
  14. like sharing, segmentation, preallocation or caching.
  15. At the lowest level, a raw memory allocator ensures that there is enough room in
  16. the private heap for storing all Python-related data by interacting with the
  17. memory manager of the operating system. On top of the raw memory allocator,
  18. several object-specific allocators operate on the same heap and implement
  19. distinct memory management policies adapted to the peculiarities of every object
  20. type. For example, integer objects are managed differently within the heap than
  21. strings, tuples or dictionaries because integers imply different storage
  22. requirements and speed/space tradeoffs. The Python memory manager thus delegates
  23. some of the work to the object-specific allocators, but ensures that the latter
  24. operate within the bounds of the private heap.
  25. It is important to understand that the management of the Python heap is
  26. performed by the interpreter itself and that the user has no control over it,
  27. even if she regularly manipulates object pointers to memory blocks inside that
  28. heap. The allocation of heap space for Python objects and other internal
  29. buffers is performed on demand by the Python memory manager through the Python/C
  30. API functions listed in this document.
  31. .. index::
  32. single: malloc()
  33. single: calloc()
  34. single: realloc()
  35. single: free()
  36. To avoid memory corruption, extension writers should never try to operate on
  37. Python objects with the functions exported by the C library: :c:func:`malloc`,
  38. :c:func:`calloc`, :c:func:`realloc` and :c:func:`free`. This will result in mixed
  39. calls between the C allocator and the Python memory manager with fatal
  40. consequences, because they implement different algorithms and operate on
  41. different heaps. However, one may safely allocate and release memory blocks
  42. with the C library allocator for individual purposes, as shown in the following
  43. example::
  44. PyObject *res;
  45. char *buf = (char *) malloc(BUFSIZ); /* for I/O */
  46. if (buf == NULL)
  47. return PyErr_NoMemory();
  48. ...Do some I/O operation involving buf...
  49. res = PyString_FromString(buf);
  50. free(buf); /* malloc'ed */
  51. return res;
  52. In this example, the memory request for the I/O buffer is handled by the C
  53. library allocator. The Python memory manager is involved only in the allocation
  54. of the string object returned as a result.
  55. In most situations, however, it is recommended to allocate memory from the
  56. Python heap specifically because the latter is under control of the Python
  57. memory manager. For example, this is required when the interpreter is extended
  58. with new object types written in C. Another reason for using the Python heap is
  59. the desire to *inform* the Python memory manager about the memory needs of the
  60. extension module. Even when the requested memory is used exclusively for
  61. internal, highly-specific purposes, delegating all memory requests to the Python
  62. memory manager causes the interpreter to have a more accurate image of its
  63. memory footprint as a whole. Consequently, under certain circumstances, the
  64. Python memory manager may or may not trigger appropriate actions, like garbage
  65. collection, memory compaction or other preventive procedures. Note that by using
  66. the C library allocator as shown in the previous example, the allocated memory
  67. for the I/O buffer escapes completely the Python memory manager.
  68. .. _memoryinterface:
  69. Memory Interface
  70. ================
  71. The following function sets, modeled after the ANSI C standard, but specifying
  72. behavior when requesting zero bytes, are available for allocating and releasing
  73. memory from the Python heap:
  74. .. c:function:: void* PyMem_Malloc(size_t n)
  75. Allocates *n* bytes and returns a pointer of type :c:type:`void\*` to the
  76. allocated memory, or *NULL* if the request fails. Requesting zero bytes returns
  77. a distinct non-*NULL* pointer if possible, as if :c:func:`PyMem_Malloc(1)` had
  78. been called instead. The memory will not have been initialized in any way.
  79. .. c:function:: void* PyMem_Realloc(void *p, size_t n)
  80. Resizes the memory block pointed to by *p* to *n* bytes. The contents will be
  81. unchanged to the minimum of the old and the new sizes. If *p* is *NULL*, the
  82. call is equivalent to :c:func:`PyMem_Malloc(n)`; else if *n* is equal to zero,
  83. the memory block is resized but is not freed, and the returned pointer is
  84. non-*NULL*. Unless *p* is *NULL*, it must have been returned by a previous call
  85. to :c:func:`PyMem_Malloc` or :c:func:`PyMem_Realloc`. If the request fails,
  86. :c:func:`PyMem_Realloc` returns *NULL* and *p* remains a valid pointer to the
  87. previous memory area.
  88. .. c:function:: void PyMem_Free(void *p)
  89. Frees the memory block pointed to by *p*, which must have been returned by a
  90. previous call to :c:func:`PyMem_Malloc` or :c:func:`PyMem_Realloc`. Otherwise, or
  91. if :c:func:`PyMem_Free(p)` has been called before, undefined behavior occurs. If
  92. *p* is *NULL*, no operation is performed.
  93. The following type-oriented macros are provided for convenience. Note that
  94. *TYPE* refers to any C type.
  95. .. c:function:: TYPE* PyMem_New(TYPE, size_t n)
  96. Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of
  97. memory. Returns a pointer cast to :c:type:`TYPE\*`. The memory will not have
  98. been initialized in any way.
  99. .. c:function:: TYPE* PyMem_Resize(void *p, TYPE, size_t n)
  100. Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n *
  101. sizeof(TYPE))`` bytes. Returns a pointer cast to :c:type:`TYPE\*`. On return,
  102. *p* will be a pointer to the new memory area, or *NULL* in the event of
  103. failure. This is a C preprocessor macro; p is always reassigned. Save
  104. the original value of p to avoid losing memory when handling errors.
  105. .. c:function:: void PyMem_Del(void *p)
  106. Same as :c:func:`PyMem_Free`.
  107. In addition, the following macro sets are provided for calling the Python memory
  108. allocator directly, without involving the C API functions listed above. However,
  109. note that their use does not preserve binary compatibility across Python
  110. versions and is therefore deprecated in extension modules.
  111. :c:func:`PyMem_MALLOC`, :c:func:`PyMem_REALLOC`, :c:func:`PyMem_FREE`.
  112. :c:func:`PyMem_NEW`, :c:func:`PyMem_RESIZE`, :c:func:`PyMem_DEL`.
  113. .. _memoryexamples:
  114. Examples
  115. ========
  116. Here is the example from section :ref:`memoryoverview`, rewritten so that the
  117. I/O buffer is allocated from the Python heap by using the first function set::
  118. PyObject *res;
  119. char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
  120. if (buf == NULL)
  121. return PyErr_NoMemory();
  122. /* ...Do some I/O operation involving buf... */
  123. res = PyString_FromString(buf);
  124. PyMem_Free(buf); /* allocated with PyMem_Malloc */
  125. return res;
  126. The same code using the type-oriented function set::
  127. PyObject *res;
  128. char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
  129. if (buf == NULL)
  130. return PyErr_NoMemory();
  131. /* ...Do some I/O operation involving buf... */
  132. res = PyString_FromString(buf);
  133. PyMem_Del(buf); /* allocated with PyMem_New */
  134. return res;
  135. Note that in the two examples above, the buffer is always manipulated via
  136. functions belonging to the same set. Indeed, it is required to use the same
  137. memory API family for a given memory block, so that the risk of mixing different
  138. allocators is reduced to a minimum. The following code sequence contains two
  139. errors, one of which is labeled as *fatal* because it mixes two different
  140. allocators operating on different heaps. ::
  141. char *buf1 = PyMem_New(char, BUFSIZ);
  142. char *buf2 = (char *) malloc(BUFSIZ);
  143. char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
  144. ...
  145. PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
  146. free(buf2); /* Right -- allocated via malloc() */
  147. free(buf1); /* Fatal -- should be PyMem_Del() */
  148. In addition to the functions aimed at handling raw memory blocks from the Python
  149. heap, objects in Python are allocated and released with :c:func:`PyObject_New`,
  150. :c:func:`PyObject_NewVar` and :c:func:`PyObject_Del`.
  151. These will be explained in the next chapter on defining and implementing new
  152. object types in C.