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;
}