I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace.
My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using gcc
).
I would like my program to be able to generate a stack trace when it crashes and the next time the user runs it, it will ask them if it is ok to send the stack trace to me so I can track down the problem. I can handle the sending the info to me but I don't know how to generate the trace string. Any ideas?
Best Solution
For Linux and I believe Mac OS X, if you're using gcc, or any compiler that uses glibc, you can use the backtrace() functions in
execinfo.h
to print a stacktrace and exit gracefully when you get a segmentation fault. Documentation can be found in the libc manual.Here's an example program that installs a
SIGSEGV
handler and prints a stacktrace tostderr
when it segfaults. Thebaz()
function here causes the segfault that triggers the handler:Compiling with
-g -rdynamic
gets you symbol info in your output, which glibc can use to make a nice stacktrace:Executing this gets you this output:
This shows the load module, offset, and function that each frame in the stack came from. Here you can see the signal handler on top of the stack, and the libc functions before
main
in addition tomain
,foo
,bar
, andbaz
.