Setting a pointer to null segfault
c, pointers, segmentation-fault
Solution
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;
Problem
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?