C++: Pragmatically Generating a Back Trace/Stack Dump

When you work on a very large embedded project with multiple developers on different continents, all dumping code into a project, it becomes very difficult to figure out what is broken and more importantly, who is the best person to go fix it.

One way is to generate core dumps and then use gdb and the bt command to print the back trace, but core files can become large and not everyone knows how to analyze a back trace. So invariably, one or two developers end up being called in on every problem where they guestimate where it may be, and assign the bug. Arguments ensue and time is wasted. It can turn into a tremendous waste of time.

If things get bad enough, I will add C++ code that will generate a back trace (sometimes referred to as a stack trace) in a human readable format. With that I can quickly say which part of the application broke, and go find the owner to assign the bug to.

If you are using Linux/gcc/glibc you can generate a back trace with the backtrace() and backtrace_symbols() function calls. Below is an example:

#include <stdio.h> 
#include <execinfo.h>

void backtrace(void) 
{    
  void *addresses[10];   
  char **strings;

    int size = backtrace(addresses, 10);
    strings = backtrace_symbols(addresses, size);
    printf("Stack frames: %d\n", size);
    for(int i = 0; i < size; i++)
     {
        printf("%d: %X\n", i, (int)addresses[i]);
        printf("%s\n", strings[i]);
     }
    free(strings);
}

This entry was posted in Software Development. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s