开发者

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.

What breakpoint can I in gdb set that will break on the error so that I can view a stack trace?

The program is a combination of C an开发者_C百科d C++, compiled with 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. 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:

 int * p = new int[50000000];

What does backtrace says when you load crash dump into gdb? If you cannot generate dump, you can ask GDB to stop when exception is thrown or caught. Unfortunately, some versions of GDB support only the following syntax:

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

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 (i.e., you're on x86 Linux), run your program in Valgrind, it can often show you exactly where the corruption happens.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜