2011-04-30 218 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 

還是使用投放新!所以它的構造函數被調用。另一方面,根的構造函數是永遠不會調用!你只是分配一個樹需要的大小的內存!

相關問題