本文介绍了Seg故障后将项目压入STL容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
typedef struct temp
{
int a,b;
char * c;
temp(){c =(char *)malloc(10);};
〜temp(){free(c);};
} temp;
int main()
{
temp a;
list< temp> l1;
l1.push_back(a);
l1.clear();
return 0;
}
解决方案
您没有复制构造函数。
你将'a'推入列表,它被复制。
因为你没有一个拷贝构造函数(为c分配内存并从旧c分配到新c)c是a中的同一个指针,而且是列表中的a的副本。
两个a的析构函数被调用,第一个将成功,第二个将失败,因为内存c指向已经被释放。
要查看发生了什么,在构造函数和析构函数中加入一些cout,然后逐步执行代码。
typedef struct temp
{
int a,b;
char *c;
temp(){ c = (char*)malloc(10);};
~temp(){free(c);};
}temp;
int main()
{
temp a;
list<temp> l1;
l1.push_back(a);
l1.clear();
return 0;
}
giving segmentation fault.
解决方案
You don't have a copy constructor.
When you push 'a' into the list, it gets copied.Because you don't have a copy constructor (to allocate memory for c and copy from old c to new c) c is the same pointer in a and the copy of a in the list.
The destructor for both a's gets called, the first will succeed, the second will fail because the memory c points to has already been freed.
You need a copy constructor.
To see whats happening, put some couts in the constructors and destructors and step through the code.
这篇关于Seg故障后将项目压入STL容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!