问题
#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;
}
回答1:
Use new instead of malloc.
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 valid tree object (with a properly initialized first member), use this:
root = new tree();
Later, when you want to release that object, use delete:
delete root;
回答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 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!
回答3:
The problem is that root doesn't point to a tree, it points to a tree-sized chunk of allocated memory. Then you try to execute a set operation on an internal member, when the set (with its internal structure and well-groomed pointers) isn't actually in there.
回答4:
malloc doesn't call the constructor, so neither tree's constructor nor std::set's constructor ever get called and you're trying to populate the unconstructed std::set. That is why you get segfault.
Use new as:
root = new tree(); //this allocates memory, and constructs the object as well.
//deallocation
delete root; //call the destructor, and then deallocate the memory
Or use 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
来源:https://stackoverflow.com/questions/5841981/why-do-i-get-a-segmentation-fault-when-i-am-trying-to-insert-into-a-tree