3 ms·
I plan to cover CPython's memory management in the future posts. In a nutshell, an object gets destroyed when its reference count hits 0. In this case, CPython
by r4victor 6y ago
I plan to cover CPython's memory management in the future posts. In a nutshell, an object gets destroyed when its reference count hits 0. In this case, CPython calls `tp_dealloc` [1] of the object's type. The `tp_dealloc` slot releases all the resources the object owns and frees the memory. The implementation of `tp_dealloc` differs for different types. Eventually, the `free` function of the memory allocator is called to free the memory. A memory allocator is a set of functions to manage memory. The default memory allocator for objects is pymalloc. It allocates small objects (<= 512 bytes) using the arena allocator [2] and falls back to the raw memory allocator otherwise. The latter calls the `free()` library function to free the memory.
The Python/C Reference Manual has a great section on memory management [3].
[1] https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_dealloc https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject....
[2] https://www.evanjones.ca/memoryallocator/ https://www.evanjones.ca/memoryallocator/
[3] https://docs.python.org/3/c-api/memory.html https://docs.python.org/3/c-api/memory.html