Search code examples
cgccundefined-behaviordereferencenull-pointer

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:

#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.