为什么PythonC扩展在重新分配后丢失了指针跟踪?

2024-10-02 10:18:22 发布

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

#include <Python.h>

int isCodeValid() {
    char *base = calloc(512, 1);
//  free(base);
//  base = calloc(512,1);
    base = realloc(512, 1);
    free(base);
    return 1;
}

static PyMethodDef CodecMethods[] = {
        { NULL, NULL, 0, NULL } };

PyMODINIT_FUNC inittest(void) {
    //check for the machine code
    //Py_FatalError

    if (isCodeValid() != 0)
        printf("nothing\n");
    else {
        printf("starting ... \n");
    }
    (void) Py_InitModule("test", CodecMethods);
}

上面是一个使用realloc的简单c扩展 这是设置.py在

^{pr2}$

编译后使用: Python2.7设置.py构建扩展--就地--强制

我得到了一个错误:

Python(30439) malloc: *** error for object 0x200: pointer being realloc'd was not allocated
*** set a breakpoint in malloc_error_break to debug

但是使用

free(base);
base = calloc(512,1);

工作正常,没有错误

有什么我搞砸了吗?在


Tags: pyfreeforbase错误errornullprintf
1条回答
网友
1楼 · 发布于 2024-10-02 10:18:22

^{}的第一个参数必须是指向以前分配的内存(或NULL)的指针,而不是int文本。512正被强制转换为一个指针,并且之前没有分配内存的抱怨是正确的。在

纠正方法:

/* Don't do this:

       base = realloc(base, 512);

   because if realloc() fails it returns NULL
   and does not free(base), resulting in memory
   remaining allocated and the code having no way
   to free it: a memory leak.
*/

char* tmp = realloc(base, 512);
if (tmp)
{
    base = tmp;
}

编译时警告级别为最大值,因为编译器将发出警告使指针来自整数或类似值。不要忽视警告,最好把它当作错误处理。在

相关问题 更多 >

    热门问题