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?
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With