How can I debug St9bad_alloc errors in gdb in C?

I have a program crash:

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

I assume this is due to malloc / free , but I don't know which one.

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

The program is a combination of C and C ++ compiled with gcc 3.4.2.

+7
c ++ c debugging gdb bad-alloc
source share
3 answers

Actually this is not malloc / free that throws an exception, it is a β€œnew” one that is definitely located in the C ++ part of your application. It looks like you are providing a parameter that is too large for the β€œnew” to host.

'std :: bad_alloc' is called by the following code, for example:

  int * p = new int[50000000]; 

What does backtrace say when you load a crash reset in gdb? If you cannot create a dump, you can ask GDB to stop when an exception is thrown or caught . Unfortunately, some versions of GDB only support the following syntax:

 catch throw 

which allows you to break the application when any exception is thrown. However, in the help you see that you can run

 catch throw std::bad_alloc 

in new versions.

And do not forget that:

(gdb) help catch

is a good source for other useful information.

+12
source share

It is possible that this is due to overwriting some memory, which leads to damage to the state of the memory allocation system (which is usually stored either before or after memory blocks are returned to the application).

If you have the opportunity (i.e. you are on x86 Linux), run your program in Valgrind , it can often show where corruption is happening.

0
source share

I had this while trying to read in a file that does not exist ... I would try to create an internal buffer for the contents of the file, but since the file did not exist, my creation of the buffer is screwed.

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

Remember the children, always initialize your variables: D and check for null cases.

0
source share

All Articles