how can I print the full call stack when a std::exception raises?
Asked
Active
Viewed 4,265 times
5
-
2No way of doing this using standard C++ - your specific compiler may have something you can use. – Jul 31 '10 at 14:14
-
which compiler are you using? – carlsborg Jul 31 '10 at 14:14
-
Which platform are you using, as well? – reece Jul 31 '10 at 14:24
-
http://stackoverflow.com/questions/691719/c-display-stack-trace-on-exception http://stackoverflow.com/questions/616653/portable-c-stack-trace-on-exception – SigTerm Jul 31 '10 at 14:25
-
I'm using g++ in debian. – MBZ Jul 31 '10 at 14:28
-
Don't think you can do this without using a debugger. Unlike languages like Java stacktrace capturing and reading isn't in the language. – seand Jul 31 '10 at 17:33
-
http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes/77336#77336 – Aug 01 '10 at 01:32
1 Answers
4
If you're using g++ (gcc) and don't mind the code being non-portable, you could try following the wise words of "tombarta":
(shameless copy from tombarta):
#include <execinfo.h>
void print_trace(FILE *out, const char *file, int line)
{
const size_t max_depth = 100;
size_t stack_depth;
void *stack_addrs[max_depth];
char **stack_strings;
stack_depth = backtrace(stack_addrs, max_depth);
stack_strings = backtrace_symbols(stack_addrs, stack_depth);
fprintf(out, "Call stack from %s:%d:\n", file, line);
for (size_t i = 1; i < stack_depth; i++) {
fprintf(out, " %s\n", stack_strings[i]);
}
free(stack_strings); // malloc()ed by backtrace_symbols
fflush(out);
}
I haven't tried this myself, so I do not know if it works.

S.C. Madsen
- 5,100
- 5
- 32
- 50