为什么我得到当我试图插入一棵树*
问题描述:
#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;
}
答
使用new
,而不是malloc
分割故障。
malloc
只分配内存,它不会以任何方式对它进行初始化,也不会构造将存在于该内存中的对象。另一方面有new
构造了C++对象。因此,要获得一个有效的tree
对象(用正确初始化first
成员),使用此:
root = new tree();
以后,当你想释放对象,使用delete
:
delete root;
答
的问题是, root
不指向tree
,它指向一个大小为tree
的已分配内存块。然后尝试在内部成员上执行set
操作时,该集合(具有其内部结构和精心修饰的指针)实际上不在那里。
答
malloc
不调用构造函数,所以也不tree
的构造也不std::set
的构造曾经被调用和你想填充未构造std::set
。这就是为什么你会遇到段错误。
使用new
为:
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
答
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 = new tree(); //this allocates memory, and constructs the object as well.
//deallocation
delete root; //call the destructor, and then deallocate the memory
还是使用投放新!所以它的构造函数被调用。另一方面,根的构造函数是永远不会调用!你只是分配一个树需要的大小的内存!