# return the previously allocated memory to the system
free(my_array)
-One important thing to remember is that blocks of memory obtained with malloc
-*must* be manually released with free when one is done with them or it won't
-be reclaimed until the python process exits. This is called a memory leak.
+Note that the C-API functions for allocating memory on the Python heap
+are generally preferred over the low-level C functions above as the
+memory they provide is actually accounted for in Python's internal
+memory management system. They also have special optimisations for
+smaller memory blocks, which speeds up their allocation by avoiding
+costly operating system calls.
+
+The C-API functions can be found in the ``cpython.mem`` standard
+declarations file::
+
+ from cpython.mem cimport PyMem_Malloc, PyMem_Realloc, PyMem_Free
+
+Their interface and usage is identical to that of the corresponding
+low-level C functions.
+
+One important thing to remember is that blocks of memory obtained with
+:c:func:`malloc` or :c:func:`PyMem_Malloc` *must* be manually released
+with a corresponding call to :c:func:`free` or :c:func:`PyMem_Free`
+when they are no longer used (and *must* always use the matching
+type of free function). Otherwise, they won't be reclaimed until the
+python process exits. This is called a memory leak.
+
If a chuck of memory needs a larger lifetime then can be managed by a
-``try..finally`` block, another helpful idiom is to tie its lifetime to a
-Python object to leverage the Python runtime's memory management, e.g.::
+``try..finally`` block, another helpful idiom is to tie its lifetime
+to a Python object to leverage the Python runtime's memory management,
+e.g.::
cdef class SomeMemory:
- cdef doube* data
+ cdef double* data
def __init__(self, number):
# allocate some memory (filled with random data)
It should be noted that Cython has special support for (multi-dimensional)
arrays of simple types via NumPy and memory views which are more full featured
and easier to work with than pointers while still retaining the speed/static
-typing benefits.
\ No newline at end of file
+typing benefits.