Archive for the ‘GCC’ Category

Debug STL errors with __GLIBCXX_DEBUG

Friday, March 13th, 2009

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: =========
======= 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!

Useful GCC-only trick: warn if return value is unused

Sunday, December 14th, 2008

So I found this useful thing that you can add to your functions on GCC compilers… basically, you add an attribute to the end of the function definition and GCC will warn anytime that function is called and the return value isn’t used. Ubuntu 8.10 has enabled this for a *ton* of system calls, and its pretty useful (except when you’re just trying to do something without bothering with error checking). Of course if you don’t like -Wall then you won’t like this either…

#ifdef __GNUC__
    #define WARN_IF_UNUSED __attribute__ ((warn_unused_result))
    #define WARN_IF_UNUSED

int some_function() WARN_IF_UNUSED;