Take the 2-minute tour ×  Excuse the beginner level of this
question. I have the following simple code, but it does not seem
to run. It gets a segmentation fault. If I replace the pointer
with a simple call to the actual variable, it runs fine... I'm
not sure why.  struct node  int x;  struct node *left;  struct
node *right;  int main()  struct node *root;  root->x = 42;
printf("Hello world. %d", root->x);  return 0;  What is wrong
with this code?  share|improve this question add comment  3
Answers  up vote 10 down vote accepted struct node *root;
root->x = 42;  You're dereferencing an uninitialized pointer. To
allocate storage for the node:  struct node *root =
malloc(sizeof(struct node));  You could also allocate a node on
the stack:  struct node root; root.x = 42; share|improve this
answer So I should prefix it with some kind of initialization?
struct node *root = new (struct node); or something? –  socks
Dec 21 '10 at 22:46 Yes, but you need a constructor for it so
that all the fields get set up properly