【问题标题】:Segfaults when trying to free pointer尝试释放指针时的段错误
【发布时间】:2018-09-19 22:11:50
【问题描述】:

我有这样的代码

void find_groupings ()

  int *bandwidths;
  int *execution_time;

  bandwidths = (int *)malloc(sizeof(int)*node_count); // node_count is glbl
  execution_time = (int *)malloc(sizeof(int)*node_count);
  //other mallocs, other code etc

  while (condition) {
    // lot of code
    find_bandwidths(bandwidths);
    find_execution_time(execution_time);
    //lot of code
  }

  free(bandwidths);
  free(execution_time);

}

“free(execution_time);”行的代码段错误

Thread 1 "vx_tutorial_exe" received signal SIGSEGV, Segmentation fault.
0xf7dd0cd9 in _int_free (av=0xf7f15780 <main_arena>, p=<optimized out>, have_lock=0) at malloc.c:4005
4005    malloc.c: No such file or directory.

我可以保证“execution_time”在 find_execution_time() 内不会超出范围 我相信我释放了我在代码中所做的每一个 malloc

还发现 execution_time 的指针值在它使用 gdb 在 free() 崩溃之前是相同的

尝试了 valgrind,但由于程序段错误,它没有帮助

这可能是什么问题?

【问题讨论】:

  • valgrind 应该可以帮助你。很明显,您已经在other code 位中丢弃了您的堆。或者也许你的 malloc 失败了。至少测试 null
  • 同意堆以某种方式损坏,并且 free() 正在崩溃,因为它遇到损坏的堆元数据。如果 valgrind 没有帮助,您可以做的另一件事是暂时开始 #ifdef 删除代码的各个部分并重新运行程序以查看崩溃是否消失。最终,您可以将其范围缩小到代码的可疑子集小到足以使错误变得明显的地方。
  • 谢谢!你能告诉我如何使用 valgrind 吗?这是我得到 vex x86->IR: unhandled instruction bytes: 0xC5 0xF8 0x10 0x83 ==7406== valgrind: Unrecognized instruction at address 0x80cf291 的响应。 ==7406== at 0x80CF291: tivxBamCreateHandleSingleNode ==7406== 您的程序刚刚尝试执行 Valgrind ==7406== 无法识别的指令。
  • 谢谢杰里米,您的建议奏效了!谢谢pm100!

标签: c segmentation-fault free


【解决方案1】:

整个问题是,在 malloc 中我用错误的类型强制转换了它

对于我将其分配为的缓冲区

buffers  = (int *)malloc(sizeof(int)*node_count);

应该是的

buffers  = (buffer *)malloc(sizeof(buffer)*node_count);

缓冲区是我代码中的一种结构类型。

这太奇怪了,它以一种无法根据错误消息找出来的方式崩溃。

谢谢杰里米!和 pm100

【讨论】:

    猜你喜欢
    • 2017-02-25
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 2016-05-08
    • 2022-11-16
    相关资源
    最近更新 更多