正确使用 PyObject_Realloc

问题描述

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

PyObject_Realloc(p != NULL,0) 不返回NULL,也不释放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;