2011-04-30 162 views
1
#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

使用new,而不是malloc分割故障。

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

root = new tree(); 

以后,当你想释放对象,使用delete

delete root; 
1

的问题是, root不指向tree,它指向一个大小为tree的已分配内存块。然后尝试在内部成员上执行set操作时,该集合(具有其内部结构和精心修饰的指针)实际上不在那里。

1

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 
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 = new tree(); //this allocates memory, and constructs the object as well. 

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

还是使用投放新!所以它的构造函数被调用。另一方面,根的构造函数是永远不会调用!你只是分配一个树需要的大小的内存!

相关问题