Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can I assign NULL to a pointer in my main function, but with the exact same code not in a other function?

I am fairly new to C and wanted to create a linked list.
For the list-elements I created a structure and wanted to initialize the head element in a function. The last element of the list shall contain a null-pointer so I know, when I reached the end. But if I initialize next to NULL inside the function, I get a "Segmentation fault (core dumped)"

I tried to Google this, but I didn’t find an answer.
After that I put the code from the function into my main and it worked. But why? It is the exact same code.

Inside function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdlib.h>

struct list_node
{
    unsigned long value;
    struct list_node *next;
};

void new_list()
{
    struct list_node *cache;
    cache->next = NULL;
}

int main()
{
    new_list();

    return 0;
}

Inside main:

#include <stdlib.h>

struct list_node
{
    unsigned long value;
    struct list_node *next;
};

int main()
{
    struct list_node *cache;
    cache->next = NULL;

    return 0;
}

>Solution :

You declared a an uninitialized pointer that has an indeterminate value.

void new_list()
{
    struct list_node *cache;
    cache->next = NULL;
}

So dereferencing the pointer

    cache->next = NULL;

invokes undefined behavior.

The same problem exists in the second program

int main()
{
    struct list_node *cache;
    cache->next = NULL;

    return 0;
}

That is the second program also has undefined behavior.

What you should do is just write

int main()
{
    struct list_node *cache = NULL;

    return 0;
}

That is initially your list is empty. So initially neither object of the type struct list_node was allocated and the pointer cache is equal to NULL.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading