segmentation fault

i am getting segmentation fault when i am trying to insert using tree*.PLEASE HELP

#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 with tree pointer 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;
}
Last edited on
closed account (1yR4jE8b)
When you allocate memory with malloc, it does not call the constructor of the class/struct. So you are dereferencing an uninitialized memory block that could be anything.

Instead of using malloc, you need to allocate with new.

The reason the second insert is not failing is because when you allocate an object on the stack without explicitly calling a constructor, the default constructor is called automatically.
Last edited on
Topic archived. No new replies allowed.