正确使用 PyObject_Realloc

Use PyObject_Realloc correctly

https://github.com/python/cpython/blob/master/Include/objimpl.h#L83

PyObject_Realloc(p != NULL, 0) does not return NULL, or free the memory at p.

PyObject_Realloc 没有释放内存。

我注意到我的程序中存在内存泄漏,该程序时不时地使用 PyObject_Realloc。

我试着用这个修复它:

PyLongObject *new = (PyLongObject *) PyObject_Realloc(obj, new_size);
if (new == NULL) {
  return PyErr_NoMemory();
}
if (new != obj) {
  PyObject_Free(obj);
}
obj = new;

但是现在我得到了 malloc 错误 pointer being freed was not allocated

我如何确保我的程序在使用 PyObject_Malloc 和 PyObject_Realloc 时不会泄漏内存?

您需要以与必须使用 realloc 完全相同的方式使用它:

PyObject *new = PyObject_Realloc(obj, new_size);

if (new == NULL) {
    // obj is still valid - so maybe you need to free it *here*
    PyObject_Free(obj);
    return PyErr_NoMemory();
}


// if a non-null pointer *was* returned, then obj was already
// freed and new points to the new memory area. Therefore
// assign it to obj unconditionally.
obj = new;