Search code examples
carrayspointersfunction-pointersrealloc

realloc() on array of function ptrs leads to SIGABRT


On my current project, I do some function-ptr collecting before running the main part of the program.

Some code:

typedef void(*ShutdownFunctionPtr)(void);
static ShutdownFunctionPtr  *shutdown_functions;
static unsigned int         shutdown_functions_cnt;

/* some stuff */
shutdown_functions      = (ShutdownFunctionPtr*) malloc(sizeof(ShutdownFunctionPtr));
shutdown_functions_cnt  = 0;

/* a function to put a functionptr into the array */
void put(void (*func)(void)) { 
    shutdown_functions = (ShutdownFunctionPtr*))realloc(shutdown_functions, sizeof(ShutdownFunctionPtr) * shutdown_functions_cnt+1);
/* put the function and increment shutdown_functions_cnt  */
}

The last line crashes everything. I currently run the program with MALLOC_CHECK_=1 or above for getting nice backtrace. But I cannot figure out where the problem is. I debugged, that the shutdown_functions is a invalid Pointer, but only on the second call of the put() function. The first call works fine!

Regards!

EDIT: For sure, I do not touch anything between the calls of put()!

EDIT:

As you want a example

typedef void(*ShutdownFunctionPtr)(void);
static ShutdownFunctionPtr *funcs;

static void foo(void);
static void bar(void);
static void register(void (*func)(void));

static void register(void (*func)(void)) {
    funcs = realloc(funcs, sizeof(ShutdownFunctionPtr) * (cnt+1));
    funcs[cnt] = func;
    cnt++;
}

int main(void) {
    funcs = malloc(sizeof(ShutdownFunctionPtr));
    register(foo);
    register(bar);
}

/* foo and bar somewere */

This is what the real code looks like.


Solution

  • There is, at least, a problem with:

    sizeof(ShutdownFunctionPtr) * shutdown_functions_cnt+1
    

    You probably meant

    sizeof(ShutdownFunctionPtr) * (shutdown_functions_cnt+1)