好奇的探索者,理性的思考者,踏实的行动者。
Table of Contents:
#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#include <signal.h>
void dump(int signo)
{"catch Segmentation fault!!!\n");
fprintf(stderr,#define SIZE 100
FILE *fh;"./dbg_msg.log", "w+")))
if(!(fh = fopen(0);
exit(100];
void *buffer[
int nptrs;
nptrs = backtrace(buffer,SIZE);
backtrace_symbols_fd(buffer, nptrs, fileno(fh));
fflush(fh);1);
exit(-
}
int main(){
signal(SIGSEGV, &dump);
char *p;
p = NULL; 'x';
*p = "%c", *p);
printf(0;
return }
打印格式
0x4010b9]
./main[.6(+0x36400)[0x7f8d88b87400]
/lib64/libc.so0x401117]
./main[.6(__libc_start_main+0xf5)[0x7f8d88b73555]
/lib64/libc.so0x400db9] ./main[
打印的是程序的地址,需要用工具把地址转成文件的行号
addr2line -e <带符号库> <内存地址>0x4010b9
addr2line -e main 0x401117
addr2line -e main 0x400db9 addr2line -e main
// 代码位置:muduo/base/CurrentThread.h
string stackTrace(bool demangle)
{
string stack;200;
const int max_frames =
void* frame[max_frames];
int nptrs = ::backtrace(frame, max_frames);
char** strings = ::backtrace_symbols(frame, nptrs);
if (strings)
{256;
size_t len = char*>(::malloc(len)) : nullptr;
char* demangled = demangle ? static_cast<1; i < nptrs; ++i) // skipping the 0-th, which is this function
for (int i =
{
if (demangle)
{// https://panthema.net/2008/0901-stacktrace-demangled/
// bin/exception_test(_ZN3Bar4testEv+0x79) [0x401909]
char* left_par = nullptr;
char* plus = nullptr;char* p = strings[i]; *p; ++p)
for (
{'(')
if (*p ==
left_par = p;'+')
else if (*p ==
plus = p;
}
if (left_par && plus)
{'\0';
*plus = 0;
int status = 1, demangled, &len, &status);
char* ret = abi::__cxa_demangle(left_par+'+';
*plus = 0)
if (status ==
{// ret could be realloc()
demangled = ret; 1);
stack.append(strings[i], left_par+
stack.append(demangled);
stack.append(plus);'\n');
stack.push_back(
continue;
}
}
}// Fallback to mangled names
stack.append(strings[i]);'\n');
stack.push_back(
}
free(demangled);
free(strings);
}
return stack; }