2013-06-28 38 views
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为什么python c扩展在realloc后丢失指针跟踪?

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

没有错误

什么我搞砸了在这里工作得很好?

+0

对不起我的错,我错过了realloc() – davyzhang

回答

2

realloc()的第一个参数必须是指向先前分配的内存(或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; 
} 

编译级警告最大因为编译器将发出一个警告使指针从整数或相似。不要忽视警告,最好把它当作错误。

+0

非常感谢,这个成语非常有用。顺便说一句,使用扩展它真的很棘手,它会改变指针的地址,如果在python/go扩展中使用,这将使go/python中的第一个分配的指针无用。必须赶上最后返回的一个来释放它。 – davyzhang