正确使用PyObject_Realloc

2024-09-28 01:33:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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时,如何确保我的程序不会泄漏内存


Tags: 内存https程序githubcomobjnewreturn
1条回答
网友
1楼 · 发布于 2024-09-28 01:33:23

您需要以与使用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;

相关问题 更多 >

    热门问题