#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; }
use new
instead of malloc
.
malloc
allocates memory, doesn't initialize in way , doesn't construct objects living in memory. new
on other had constructs c++ objects. valid tree
object (with initialized first
member), use this:
root = new tree();
later, when want release object, use delete
:
delete root;
Comments
Post a Comment