Debug STL errors with __GLIBCXX_DEBUG

Ever got one of those *really* annoying glibc errors that don’t give you a whole lot of information except “something bad happened, and it was memory related, but we’re not going to tell you where the problem is!”? You know, in the form of

*** glibc detected *** ./test: double free or corruption (out): 0x0000000001e52440 ***
======= Backtrace: =========
/lib/libc.so.6[0x7f27a9fd5a58]
/lib/libc.so.6(cfree+0x76)[0x7f27a9fd80a6]
./test[0x401e51]
./test[0x401e83]
./test[0x402118]
./test[0x402159]
./test[0x40155b]
./test[0x40167d]
/lib/libc.so.6(__libc_start_main+0xe6)[0x7f27a9f7a466]
./test[0x400cd9]
======= Memory map: ========
... and so on ...

I’ve encountered this cryptic and annoying error (I mean c’mon, usually the memory addresses referenced in the trace don’t resolve to anything in gdb) a few times for really random and weird memory-related errors, many times when I’m doing something with the STL.

Turns out, you can define __GLIBCXX_DEBUG in your program (using -D__GLIBCXX_DEBUG on the g++ command line), and instead of an annoying message you may get an assert that is far more helpful and looks like this:

/usr/include/c++/4.3/debug/vector:267:error: attempt to access an element
    in an empty container.

Objects involved in the operation:
sequence "this" @ 0x0x7fff5ee0f420 {
  type = NSt7__debug6vectorIiSaIiEEE;
}

Now at least you know what you did wrong. However, for optimal usage you should be attached with GDB, and then as soon as the error occurs you can do a backtrace with the debugger and you should know exactly where the bug is. The only caveat is that there is a noticeable performance hit when you enable this (especially if you use the STL heavily), so in general you don’t want to define it all the time.

Hope that saves you some time! I know it helped me!

Leave a Reply