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 (to 0, most likely). This is C++ so patterns are different from C. –  Steve Townsend Dec 21 '10 at 22:49
In this particular case I would declare a struct node root rather than a pointer and then use root.x and pass &root to functions that expect a pointer. Not always is dynamic storage justified. –  Blagovest Buyukliev Dec 21 '10 at 22:50
add comment

In order to use a pointer to access something, the pointer must be pointing at that something. In order for the pointer to be pointing at that something, that something must exist. Creating a pointer does not create anything for it to point at. You must do so explicitly, either by dynamic allocation (malloc()), stack allocation (i.e. a local variable) or by pointing to something that already exists (e.g. a static instance, such as a global; a value that was passed in as a parameter; etc.).

share|improve this answer
add comment

After struct node *root; line add the

root = (sturct node*) malloc(sizeof(struct node));

Also, before Return 0 line add the

share|improve this answer
add comment

Your Answer


