【问题标题】:realloc() on array of function ptrs leads to SIGABRT函数 ptrs 数组上的 realloc() 导致 SIGABRT
【发布时间】:2013-01-26 16:53:08
【问题描述】:

在我当前的项目中,我在运行程序的主要部分之前进行了一些函数-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 是一个无效的指针,但仅在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 */

这才是真正的代码。

【问题讨论】:

  • 你能想出一个最小的独立示例来演示这个问题吗?
  • 正如 NPE 上面所说,我们需要看看 put() 函数的第一次和第二次调用之间发生了什么
  • 您的代码语法甚至无效。
  • @netcoder 好吧,这只是有点伪 C 的东西。但是您在上面示例中看到的行没有改变,只是这里缺少上下文。

标签: c arrays pointers function-pointers realloc


【解决方案1】:

至少存在以下问题:

sizeof(ShutdownFunctionPtr) * shutdown_functions_cnt+1

你可能是说

sizeof(ShutdownFunctionPtr) * (shutdown_functions_cnt+1)

【讨论】:

  • 真丢脸!这太尴尬了!
  • @musicmatze 如果我修改您的新版本以使其编译,它不会出现段错误。
猜你喜欢
  • 1970-01-01
  • 2015-07-08
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多