9.2 Memory Interface

The following function sets, modeled after the ANSI C standard, are available for allocating and releasing memory from the Python heap:

ANY*
The type used to represent arbitrary blocks of memory. Values of this type should be cast to the specific type that is needed.

ANY* PyMem_Malloc (size_t n)
Allocates n bytes and returns a pointer of type ANY* to the allocated memory, or NULL if the request fails. Requesting zero bytes returns a non-NULL pointer.

ANY* PyMem_Realloc (ANY *p, size_t n)
Resizes the memory block pointed to by p to n bytes. The contents will be unchanged to the minimum of the old and the new sizes. If p is NULL, the call is equivalent to PyMem_Malloc(n); if n is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-NULL. Unless p is NULL, it must have been returned by a previous call to PyMem_Malloc() or PyMem_Realloc().

void PyMem_Free (ANY *p)
Frees the memory block pointed to by p, which must have been returned by a previous call to PyMem_Malloc() or PyMem_Realloc(). Otherwise, or if PyMem_Free(p) has been called before, undefined behaviour occurs. If p is NULL, no operation is performed.

ANY* Py_Malloc (size_t n)
Same as PyMem_Malloc(), but calls PyErr_NoMemory() on failure.

ANY* Py_Realloc (ANY *p, size_t n)
Same as PyMem_Realloc(), but calls PyErr_NoMemory() on failure.

void Py_Free (ANY *p)
Same as PyMem_Free().

The following type-oriented macros are provided for convenience. Note that TYPE refers to any C type.

TYPE* PyMem_NEW (TYPE, size_t n)
Same as PyMem_Malloc(), but allocates (n * sizeof(TYPE)) bytes of memory. Returns a pointer cast to TYPE*.

TYPE* PyMem_RESIZE (ANY *p, TYPE, size_t n)
Same as PyMem_Realloc(), but the memory block is resized to (n * sizeof(TYPE)) bytes. Returns a pointer cast to TYPE*.

void PyMem_DEL (ANY *p)
Same as PyMem_Free().


Send comments on this document to python-docs@python.org.