Use the backtrace function to print the call stack.

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.