-2

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;
Mat
  • 202,337
  • 40
  • 393
  • 406
  • 2
    Pick a book from [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Mar 25 '17 at 12:55
  • 1
    Looks like a case of learning `C` instead of `C++`. The `typedef struct` is an indication of this. In `C++`, there is no need for `typedef struct`, just `struct node { string str; };`, and using `malloc` was covered in the answer below. – PaulMcKenzie Mar 25 '17 at 13:14
  • Eeeek, that looks more like C compiled with a C++ compiler than proper C++. Don't use `malloc` and break out of that `typedef struct` habit. – Jesper Juhl Mar 25 '17 at 15:46

1 Answers1

5

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;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621