为什么当我尝试插入树时会出现分段错误*
#include<iostream>
#include<set>
#include<stdlib.h>
using namespace std;
typedef set<short> pos;
typedef struct tree
{
pos first;
}tree;
class check
{
public:
pos last;
void check_set();
};
void check::check_set()
{
tree *root,p;
root=(tree*)malloc(sizeof(tree));
root->first.insert(2);//SEGMENTATION FAULT HERE WHY???
p.first.insert(3);//NO SEGMENTATION FAULT
}
int main()
{
check obj;
obj.check_set();
obj.last.insert(1);//NO ERROR HERE
return 0;
}
#include<iostream>
#include<set>
#include<stdlib.h>
using namespace std;
typedef set<short> pos;
typedef struct tree
{
pos first;
}tree;
class check
{
public:
pos last;
void check_set();
};
void check::check_set()
{
tree *root,p;
root=(tree*)malloc(sizeof(tree));
root->first.insert(2);//SEGMENTATION FAULT HERE WHY???
p.first.insert(3);//NO SEGMENTATION FAULT
}
int main()
{
check obj;
obj.check_set();
obj.last.insert(1);//NO ERROR HERE
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
new
而不是malloc
。malloc 仅分配内存,不会以任何方式初始化内存,也不会构造将位于该内存中的对象。另一方面的
new
构造了 C++ 对象。因此,要获取有效的tree
对象(具有正确初始化的first
成员),请使用以下命令:稍后,当您想要释放该对象时,请使用
delete:
Use
new
instead ofmalloc
.malloc
only allocates memory, it doesn't initialize it in any way and doesn't construct the objects that will be living in that memory.new
on the other had constructs C++ objects. So to get a validtree
object (with a properly initializedfirst
member), use this:Later, when you want to release that object, use
delete
:p 分配在堆栈上!所以它的构造函数被调用。另一方面,root 的构造函数从不被调用!您只需分配树所需大小的内存即可!
p is allocated on the stack! So it's constructor is called. root's constructor on the other hand is never called! You just allocate a memory of the size a tree would need!
问题在于根并不指向树,而是指向树大小的已分配内存块。然后,当集合(及其内部结构和精心修饰的指针)实际上并不在那里时,您尝试对内部成员执行
set
操作。The problem is that
root
doesn't point to atree
, it points to atree
-sized chunk of allocated memory. Then you try to execute aset
operation on an internal member, when the set (with its internal structure and well-groomed pointers) isn't actually in there.malloc
不会调用构造函数,因此tree
的构造函数和std::set
的构造函数都不会被调用,并且您尝试填充未构造std::set
。这就是为什么你会出现段错误。使用
new
作为:或使用placement-new作为:
malloc
doesn't call the constructor, so neithertree
's constructor norstd::set
's constructor ever get called and you're trying to populate the unconstructedstd::set
. That is why you get segfault.Use
new
as:Or use placement-new as: