Here is the code which I am trying to run -
typedef struct node{
string str;
}node;
string s = "";
node *t = (node *)malloc(sizeof(node));
t->str = s ; // if s is empty, this statement gives segmentation fault.
cout<<t->str<<endl;
Here is the code which I am trying to run -
typedef struct node{
string str;
}node;
string s = "";
node *t = (node *)malloc(sizeof(node));
t->str = s ; // if s is empty, this statement gives segmentation fault.
cout<<t->str<<endl;
In C++ you should never use malloc to allocate objects with constructors. The malloc function only allocates memory, but it doesn't cause the constructors to be called.
That means your str member is uninitialized and you have undefined behavior when using it.
If you really need to allocate dynamically use new instead:
node* t = new node;