简体   繁体   English

如何在C中调试gdb中的St9bad_alloc故障?

[英]How can I debug St9bad_alloc failures in gdb in C?

I have a program failing with: 我有一个程序失败:

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

I imagine it's something to do with malloc / free , but I don't know which one. 我想这与malloc / free ,但我不知道哪一个。

What breakpoint can I in gdb set that will break on the error so that I can view a stack trace? 我可以在gdb中设置什么断点来破坏错误,以便我可以查看堆栈跟踪?

The program is a combination of C and C++, compiled with gcc 3.4.2. 该程序是C和C ++的组合,使用gcc 3.4.2编译。

It is not really malloc/free which causes the exception, it is "new" which is definitely in C++ part of your application. 它不是真正的malloc / free导致异常,它是“new”,它绝对是你应用程序的C ++部分。 It looks like you are providing a parameter which is too big for "new" to allocate. 看起来您提供的参数太大而无法分配“新”。

'std::bad_alloc' is caused by the following code for example: 'std :: bad_alloc'是由以下代码引起的,例如:

 int * p = new int[50000000];

What does backtrace says when you load crash dump into gdb? 将崩溃转储加载到gdb时,backtrace会说什么? If you cannot generate dump, you can ask GDB to stop when exception is thrown or caught . 如果无法生成转储,则可以在抛出或捕获异常时让GDB停止。 Unfortunately, some versions of GDB support only the following syntax: 不幸的是,某些版本的GDB仅支持以下语法:

catch throw

which allows you to break application when any exception is thrown. 它允许您在抛出任何异常时中断应用程序。 However, in help you see that it should be possible to run 但是,在帮助中,您会看到它应该可以运行

catch throw std::bad_alloc

in newer versions. 在较新的版本中。

And don't forget that: 不要忘记:

(gdb) help catch (gdb)帮忙抓住

is a good source for other useful information. 是其他有用信息的良好来源。

It's quite possible that this happens due to some memory being overwritten, thus corrupting the memory allocation system's state (which is generally kept either before or after the memory blocks returned to the application). 很可能由于某些内存被覆盖而发生这种情况,从而破坏了内存分配系统的状态(通常在内存块返回应用程序之前或之后保留)。

If you have the possibility (ie, you're on x86 Linux), run your program in Valgrind , it can often show you exactly where the corruption happens. 如果您有可能(即,您使用的是x86 Linux),请在Valgrind中运行您的程序,它通常可以准确显示损坏发生的位置。

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. 记住孩子,总是初始化你的变量:D并检查零个案例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM