您的位置:首页 > 其它

检测异常并打印堆栈

2010-12-22 09:28 288 查看
#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <execinfo.h>
#include <stdio.h>
using namespace std;
static void print_stack(void)
{
void *array[10];
char **strings;
int arrsize = backtrace (array, 10);
int i;
strings = backtrace_symbols (array, arrsize);
for (i = 1; i < arrsize; i++)
{
printf (" --> %s/n", strings[i]);
}
printf ("/n");
free (strings);
}
static void sig_handle(int sig)
{
cout<<"Capture seg fault..."<<endl;
print_stack();
exit(0);
}
class A
{
public:
void get_type()
{
cout<<"called:"<<m<<endl;
}
private:
int m;
};
int entry_func()
{

try
{
signal(SIGSEGV,sig_handle);
A* ptoA = NULL;
ptoA->get_type();
}
catch(int)
{
cout<<"excption... int ..."<<endl;
}
catch(...)
{
cout<<"execption..."<<endl;
}
return 0;
}
int main()
{
entry_func();
return 0;
}


运行可执行程序时偶尔会遇到段错误,实际上是捕捉到了SIGSEGV信号,然后会打印出熟悉的Segmentation fault...但是又没有其他的信息,很不好调试...因此写个小工具来捕捉段错误的信号,然后注册一个sighandler,来处理,并打印出相应的堆栈...就能马上知道出错的函数的名字了...

哈哈```很方便吧...``
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: