>> main >> Tips & Articles >> Linux Tips & Tricks >> Printing back trace of functions inside a program

Printing back trace of functions inside a program

Suppose you have a software that gets segmentation faults, the default behavior is to terminate the application, however if your application runs on a remote system, you need a way to find out why and where you got the segmentation fault.
One way is of course to generate a core dump and later use gdb with the bt command to print the stack back trace, however a core dump is a large file consuming disk space and if you have several crashes of the application you need a way to log errors.
One such a way is to use the backtrace() function in your program to print the last functions addresses.
Of course function addresses are not exactly what you want but you can get the function names by searching the map file generated by your linker (option -Map filename to linker).
You can trap the SIGSEGV and call a function that will print the backtrace.
The following code shows a function to print the last 10 functions on the stack:


#include
#include /* for backtrace */

void bt(void) {
    int c, i;
    void *addresses[10];


    c = backtrace(addresses, 10);
    printf("backtrace returned: %dn", c);
    for(i = 0; i < c; i++) {
        printf("%d: %Xn", i, (int)addresses[i]);
    }
}


Note: After this tip was published I got the following tip from Rami Rosen:
You can use the backtrace_symbols if you use the -rdynamic switch to gcc so the program will look as follows:
#include
#include /* for backtrace */

void bt(void) {
    int c, i;
    void *addresses[10];
    char **strings;

    c = backtrace(addresses, 10);
    strings = backtrace_symbols(addresses,c);
    printf("backtrace returned: %dn", c);
    for(i = 0; i < c; i++) {
        printf("%d: %X ", i, (int)addresses[i]);
        printf("%sn", strings[i]); }
    }
 
Thanks again to Rami Rosen for the tip.

This of course prints to the standard out, but it would be easy to change it to print to a log file.
You can call this function from a signal handler.
To set a signal handler use the signal() function.

Add comment
 
8779365521  imran.khan 01/01/1970 00:00:00


Add comment      
8779365521  imran.khan 01/01/1970 00:00:00


Add comment      
8779365521  imran.khan 01/01/1970 00:00:00


Add comment      
7208245499  imran.khan 01/01/1970 00:00:00


Add comment