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()のポインタでなければなりません。はポインタにキャストされており、メモリが以前に割り当てられていないという苦情は正しいです。intNULL512

なおす:

/* 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 に答える