9

我有一个程序失败:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  St9bad_alloc

我想这与malloc/有关free,但我不知道是哪一个。

我可以在 gdb 中设置哪些断点来中断错误,以便我可以查看堆栈跟踪?

该程序是 C 和 C++ 的组合,使用 gcc 3.4.2 编译。

4

3 回答 3

14

导致异常的并不是真正的 malloc/free,它是“新的”,它肯定在您的应用程序的 C++ 部分中。看起来您提供的参数对于“新”而言太大而无法分配。

'std::bad_alloc' 是由以下代码引起的,例如:

 int * p = new int[50000000];

当您将故障转储加载到 gdb 时,回溯会说什么?如果无法生成转储,可以在抛出或捕获异常时要求 GDB 停止。不幸的是,某些版本的 GDB 仅支持以下语法:

catch throw

这允许您在引发任何异常时中断应用程序。但是,在帮助您看到它应该可以运行

catch throw std::bad_alloc

在较新的版本中。

不要忘记:

(gdb) 帮助捕捉

是其他有用信息的良好来源。

于 2009-11-02T10:03:06.903 回答
0

I have had this when trying to read in a file that doesn't exist... I'd try to create an internal buffer for the file contents, but because the file didn't exist, my creation of the buffer screwed up.

int lenth_bytes;
length_bytes = in_file.tellg();
new char [length_bytes]; // length_bytes hadn't been initialised!!!!

Remember kids, always initialise your variables :D and check for zero cases.

于 2011-01-20T12:29:13.580 回答
0

这很可能是由于某些内存被覆盖,从而破坏了内存分配系统的状态(通常在内存块返回应用程序之前或之后保留)。

如果您有可能(例如,您在 x86 Linux 上),在Valgrind中运行您的程序,它通常可以准确地显示损坏发生的位置。

于 2009-11-02T10:01:14.360 回答