0
#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 扩展 这里是 setup.py

# coding=utf-8
from distutils.core import setup, Extension
import os

cfd = os.path.dirname(os.path.abspath(__file__))


module1 = Extension('test', sources=["test.c"])

setup(name='test', version='0.2', description='codec for test',
      ext_modules=[module1],)

import test

编译后:python2.7 setup.py build_ext --inplace --force

我得到错误:

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);

工作正常没有错误

我在这里搞砸了什么?

4

1 回答 1

2

的第一个参数realloc()必须是指向int先前分配的内存(或NULL)的指针,而不是文字。被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;
}

以最大警告级别编译,因为编译器将发出警告,使指针来自整数或类似。并且不要忽略警告,最好将其视为错误。

于 2013-06-28T10:08:56.053 回答