您的位置:首页 > 编程语言 > C语言/C++

c++中几个段错误调试记录

2017-06-05 15:24 387 查看
1  线程中调用一个外部函数出现 段错误,但是在主线程中却正常

解决方法:将该线程的stack_size设置大一点,因为外部函数可能需要的内存资源比较多,默认的stack_size不够

设置方法如下:

bool start(void*(*thread_proc)(void*),void* arg,size_t stack_size=16*1024){
pthread_attr_t attr;
size_t stacksize;
pthread_attr_init(&attr);

pthread_attr_setstacksize(&attr,stack_size);
int res=pthread_create(&thread,&attr,thread_proc,(void*)arg);
if(res!=0)
{
thread=0;
}
return res==0;
}

2  pthread_create 方法传入的方法只能是一个静态方法,如果需要用成员函数,可以在类里添加一个static的中间方法,将对象当作参数传进去,在中间方法中调用对象的方法即可。

申明:

static void* thread_proc_callback(void* arg);
void proc_callback();
实现:
void CCamera::proc_callback()
{
cout<<"proc_callback enter...."<<endl;
this->thread_event_ready=true;

imgframe* item;
while(!disqueue->stop)
{
item=disqueue->remove();//will loop to get item until success
if(item!=NULL)
OnSensorData(*item);
delete item;
}
cout<<"proc_callback exit...."<<endl;
}

void* CCamera::thread_proc_callback(void* arg)
{
((CCamera*)arg)->proc_callback();
}
调用:
thread_event.start(thread_proc_callback,(void*)this)
记得最后一个参数this,否则proc_callback()里面将会出现this=0,段错误。

3  pure virtual method called 错误

如果父类中有一个纯虚函数,子类实现,父类中有个线程在持续调用该虚函数。在构析该对象时,就会出现调用纯虚函数的错误,这是因为,构析的时候,子类先进行构系,因此方法的子类实现被构析,线程里面调用时,只能调用父类的了,但是父类中是纯虚函数。

解决方法,要么在父类中实现纯虚函数,要么构析前先将线程kill掉
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++