Question

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

above is a simple c extension using realloc here is the 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

after compile with: python2.7 setup.py build_ext --inplace --force

I get the error :

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

but using

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

works fine without error

Anything I messed up here?

Was it helpful?

Solution

The first argument to realloc() must be a pointer, not an int literal, to a previously allocated memory (or NULL). The 512 is being cast to a pointer and the complaint is correct that the memory was not previously allocated.

To correct:

/* 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;
}

Compile with warning level at maximum as the compiler will emit a warning makes pointer from integer or similar. And don't ignore the warnings, preferably treat as errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top