Glibc provides the backtrace library function to print the call stack. For example, we can register some common signal in the program, such as sigsegment and sigpipe, and then print the call stack using backtrace In the callback functions of these signals, which makes debugging very convenient. Backtrace is easy to use. Use the example code in the man manual. For example: Char strbuffer [1024];
Int errcode;
Int btnum = 0;
Void * btbuf [100];
Char ** btstrings = NULL;
Int I;
/* Get backtrace */
Btnum = backtrace (btbuf, 100 );
Btstrings = backtrace_symbols (btbuf, btnum );
Errcode = errno;
If (btstrings = NULL ){
Sprintf (strbuffer, "alpclose get backtrace failed. errcode: % d, error Description: % s \ n ",
Errcode, strerror (errcode ));
} Else {
Sprintf (strbuffer, "backtraces, Total % d items \ n", btnum );
Fputs (strbuffer, OUTFILE );
For (I = 0; I <btnum; I ++ ){
Sprintf (strbuffer, "% s \ n", btstrings [I]);
Fputs (strbuffer, OUTFILE );
}
Free (btstrings );
}
First, use backtrace to generate a call stack of up to 100 layers. Then, use backtrace_symbols to translate a bunch of addresses returned by backtrace into function names. The return value of Backtrace is the specific number of call stacks generated. The filled btbuf is an array of void *, where each element is a void *, which is actually an address.
The strings generated by backtrace_symbols are all malloc, but do not free them one by one. Because backtrace_symbols stores the result strings in one memory based on the call stack layers given by backtrace, so, like the code above, you only need to get the free backtrace_symbols return pointer at the end. This is also mentioned in manual of Backtrace.