Senior LevelPython
In CPython C extensions, what causes fatal segmentation faults or memory leaks when handling Py_INCREF and Py_DECREF ownership rules?
❓ Interview Prompt: Explain CPython C-API, reference counting ownership rules (New References vs Borrowed References), `Py_INCREF`, `Py_DECREF`, and Segmentation Faults.
When writing CPython C extensions, memory management requires manual reference counting:
Ownership Rules:
1
New Reference ('Py_INCREF'): You own the reference and MUST call 'Py_DECREF()' when finished to prevent Memory Leaks.
2
Borrowed Reference: You do NOT own the reference. Calling 'Py_DECREF()' prematurely deallocates the object while C code still points to it, triggering fatal Segmentation Faults ('SIGSEGV')!
Code Implementation Example
c
// CPython C-API Reference Counting
PyObject* create_string(void) {
PyObject* str = PyUnicode_FromString("Hello CPython");
Py_INCREF(str); // Increment reference count (New Reference)
return str;
}💡Managing CPython C-API reference counts with Py_INCREF.
🎯 Interview Key Takeaway
Strictly manage Py_INCREF and Py_DECREF in C extensions to prevent memory leaks and Segmentation Fault crashes.
#CPython C-API#Py_INCREF#Py_DECREF#Memory Management#Senior
Back to all Python Questions→