2013-06-28 37 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