How to get the function call stack information in C++ code
This article mainly introduces "how to get function call stack information in C++ code". In daily operation, I believe many people have doubts about how to obtain function call stack information in C++ code. I have consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "how to get function call stack information in C++ code". Next, please follow the editor to study!
I. Preface
Crash is a very serious problem in the process of program execution, and these problems should generally be eliminated in the testing phase, but there will always be mistakes that will be brought to the release phase.
Therefore, the log system of the program needs to detect this situation and obtain the function call stack information when the code crashes, so as to provide effective information for debug.
Second, Linux platform 1. Register the handler of the exception signal
What abnormal signals need to be handled?
# include # include # include const std::map Signals = {{SIGINT, "SIGINT"}, {SIGABRT, "SIGABRT"}, {SIGFPE, "SIGFPE"}, {SIGILL, "SIGILL"}, {SIGSEGV, "SIGSEGV"} / / other signals can be added}
Register signal processing function
Struct sigaction action; sigemptyset (& action.sa_mask); action.sa_sigaction = & sigHandler; action.sa_flags = SA_SIGINFO; for (const auto & sigPair: Signals) {if (sigaction (sigPair.first, & action, NULL) < 0) fprintf (stderr, "Error: sigaction failed!\ n");} 2. Catch exception and get function call stack information void sigHandler (int signum, siginfo_t * info, void * ctx) {const size_t dump_size = 50; void * array [dump _ size]; int size = backtrace (array, dump_size); char * * symbols = backtrace_symbols (array, size); std::ostringstream oss; for (int I = 0; I < size; + + I) {char * mangleName = 0 Char * offsetBegin = 0; char * offsetEnd = 0; for (char * p = symbols [I]; * p; + p) {if ('= = * p) {mangleName = p;} else if ('+'= = * p) {offsetBegin = p } else if (')'= * p) {offsetEnd = p; break;}} if (mangleName & & offsetBegin & & offsetEnd & & mangleName < offsetBegin) {* mangleName++ ='\ 0mm; * offsetBegin++ ='\ 0' * offsetEnd++ ='\ 0mm; int status; char * realName = abi::__cxa_demangle (mangleName, 0,0, & status); if (0 = = status) oss