当我尝试插入树时,为什么会出现分段错误*

时间:2011-04-30 13:16:25

标签: c++ segmentation-fault

#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;
}

4 个答案:

答案 0 :(得分:4)

使用new代替malloc

malloc只分配内存,它不以任何方式初始化它,也不构造将存在于该内存中的对象。另一方面new构造了C ++对象。因此,要获得有效的tree对象(使用正确初始化的first成员),请使用以下命令:

root = new tree();

稍后,当您想要发布该对象时,请使用delete

delete root;

答案 1 :(得分:2)

tree *root,p;
root=(tree*)malloc(sizeof(tree));
root->first.insert(2);//SEGMENTATION FAULT HERE WHY???
p.first.insert(3);//NO SEGMENTATION FAULT

p在堆栈上分配!所以它的构造函数被调用。另一方面,root的构造函数是从不调用!你只需要分配一个树所需大小的内存!

答案 2 :(得分:1)

问题是root没有指向tree,它指向一个tree大小的已分配内存。然后你尝试在内部成员上执行set操作,当集合(具有内部结构和训练有素的指针)实际上不在那里时。

答案 3 :(得分:1)

malloc不会调用构造函数,因此tree的构造函数和std::set的构造函数都不会被调用,并且您正在尝试填充未构造的< / em> std::set。这就是你遇到段错误的原因。

new用作:

root = new tree(); //this allocates memory, and constructs the object as well.

//deallocation
delete root; //call the destructor, and then deallocate the memory

或使用placement-new as:

root=(tree*)malloc(sizeof(tree)); //only allocates memory
root = new (root) tree; //constructs the object in the memory pointed to by root.

//deallocation
root->~tree(); //call the destructor
free(root);  //and then deallocate the memory