C API's Top 3 Memory Management Pitfalls

Developers often struggle with correct reference counting (Py_INCREF/Py_DECREF) to prevent memory leaks or crashes, managing object ownership transfers, and distinguishing between Python's object heap and C's native memory allocations.

The top 3

  1. Reference Counting: The Top Cause of Leaks: Mismatched `Py_INCREF` and `Py_DECREF` calls are the most frequent source of memory leaks and crashes in Python C extensions, often stemming from incorrect handling of 'new' versus 'borrowed' references.
  2. Allocator Mismatch: Mixing Python and C Heaps: Using C standard library allocators like `malloc()` with Python's `PyMem_Malloc()` for Python objects or internal buffers leads to undefined behavior and fatal memory corruption, as they operate on different memory heaps.
  3. Native Resource Leaks: Beyond Python Objects: C extensions often allocate native memory or resources (e.g., file handles, raw buffers) directly with C's `malloc` that Python's garbage collector cannot track, requiring careful manual `free()` calls, especially in error handling paths, to prevent leaks.

Sources

Open the full topic