私の現在のプロジェクトでは、プログラムの主要部分を実行する前に、いくつかのfunction-ptr収集を実行します。
いくつかのコード:
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 */
}
最後の行はすべてをクラッシュさせます。私は現在、MALLOC_CHECK_ = 1以上でプログラムを実行して、優れたバックトレースを取得しています。しかし、どこに問題があるのかわかりません。が無効なポインタであることをデバッグしましたshutdown_functions
が、関数の2回目の呼び出しでのみput()
です。最初の呼び出しは正常に機能します。
よろしく!
put()
編集:確かに、私は!の呼び出しの間に何も触れません。
編集:
あなたが例を望むように
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 */
これは実際のコードがどのように見えるかです。