What are some of the reasons that segmentation faults occur? In the following code I am trying to create an easy way to use linked lists. Basically in my program you just create a list using the linkedList struct type. However, there is a line in the program that causes a segmentation fault. Why does this happen? Any help would be much appreciated. Thank you :)
#include <stdio.h>
#include <stdlib.h>
struct node{
int num;
struct node *next;
};
//Make the struct
typedef struct {
struct node * first;
struct node * current;
}linkedList;
void addNode(linkedList list, int a);
void addFirstNode(linkedList list, int b);
//Function prototypes
int main() {
linkedList list;
addFirstNode(list, 1);
addNode(list, 2);
addNode(list, 3);
addNode(list, 4);
addNode(list, 5);
addNode(list, 6);
addNode(list, 7);
}
void addFirstNode(linkedList list, int input) {
list.first = (struct node *)malloc(sizeof(struct node)); //Make first node
list.first -> num = input; //Fill first node
list.current = list.first;
}
void addNode(linkedList list, int input) {
struct node * newNode = (struct node *)malloc(sizeof(struct node));
newNode -> num = input;
list.current -> next = newNode; //Segmentation fault! (core dumped)
list.current = newNode;
}