4

I have a struct called node as follows:

struct node {
    int data;
}

stored in some structure:

struct structure {
  struct node *pointer;
}

I'm trying to set pointer to NULL as follows:

struct structure *elements;
elements->pointer = NULL;

Why does this segfault? Does it actually attempt to dereference the pointer before setting it to null?

When I switch elements from a pointer to the actual struct and do the following:

struct structure elements;
elements.pointer = NULL;

It stops segfaulting and works. Why doesn't setting a pointer to null work?

1
  • 2
    wow, this question was resolved quickly Commented Jul 2, 2012 at 14:29

5 Answers 5

7
struct structure *elements;
elements->pointer = NULL;

elements pointer points to nowhere. Dereferencing an invalid pointer (elements pointer) is undefined behavior.

You need to initialize elements pointer to a valid object, like:

struct structure my_struct;
struct structure *elements = &my_struct;
elements->pointer = NULL;
Sign up to request clarification or add additional context in comments.

Comments

4

You need to initialize the pointer

struct structure *elements = malloc(sizeof(struct structure));

If you don't do this it will point to a arbitrary memory location.

Comments

2

The invalid pointer you're derefrencing, thus the segfault, is not elements->pointer, but elements itself. Since it has not been set (e.g.: by a malloc), it could point to any location in memory.

1 Comment

He's dereferencing an uninitialized pointer. It may or may not be NULL.
1

you didn't initialize *elements.

*elements right now points to nothing, so elements->pointer is dereferencing nothing, which gives you your segfault.

2 Comments

He's dereferencing an uninitialized pointer. It may or may not be null.
Stop downvoting everyone on a technicality, @Graham, and I've editted my answer.
0

elements hasn't been initialized to point to anything yet.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.