I made a c++ app, but it keeps dying by itself.
stacktrace
I want to see what's going on
I've only heard of it, but I don't know how
My app uses linux
/window
/mac
Compiled all to gcc
.
After the app dies, when the user turns on the app,
I'd like to ask the user and get a stack trace
.
I can plan to get information I don't know how to save trace information. Help me
c++ gcc crash stack-trace assert
If you are writing the glibc
or gcc
compiler in linux
/OSX
, you can write the backtrack() function in the
execinfo.h
header.
backtrace()
outputs stacktrace
when segmentation fault
occurs and exit
.
Refer to libc manual for related documents
I will set the SIGSEGV handler and attach a code that prints the stacktrace to stderr when segfault occurs. *Segfault occurs in baz() function and calls handler
#include <stdio.h>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
void handler(int sig) {
void *array[10];
size_t size;
// Gets all void* entries in the stack
size = backtrace(array, 10);
// Output all frames to stderr
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
void baz() {
int *foo = (int*)-1; // purposely make a weird pointer
printf("%d\n", *foo); // generate segfault
}
void bar() { baz(); }
void foo() { bar(); }
int main(int argc, char **argv) {
signal(SIGSEGV, handler); // signal handler settings
foo(); // segfault occurred!
}
The gcc
option -g -rdynamic
outputs symbol
to stacktrace
. It's easier to see.
$ gcc -g -rdynamic ./test.c -o test
When compiled into , the results are as follows:
`$ ./test
Error: signal 11:
./test(handler+0x19)[0x400911]
/lib64/tls/libc.so.6[0x3a9b92e380]
./test(baz+0x14)[0x400962]
./test(bar+0xe)[0x400983]
./test(foo+0xe)[0x400993]
./test(main+0x28)[0x4009bd]
/lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb]
./test[0x40086a]
You can check modules, offsets, and functions Can you see the signal handler on the stack top, and as you go underneath it, other functions appear?
© 2024 OneMinuteCode. All rights reserved.