Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a pointer to null segfault

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?

like image 667
darksky Avatar asked Dec 08 '22 23:12

darksky


2 Answers

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;
like image 61
ouah Avatar answered Feb 05 '23 02:02

ouah


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.

like image 37
RedX Avatar answered Feb 05 '23 01:02

RedX