I need to create a linked list of nodes such that the main function is able to work; I cannot change anything in the main function. I am new to C, so I am probably making a simple mistake or two, and I am getting a segmentation fault when I try to run my code. Am I missing something obvious?
The segmentation fault happens on marked line
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
char *value;
struct Node *next;
}Node;
typedef struct Node** List;
Node *new_node(char *input);
void delete_node(Node *input);
void push(List list, char *value);
List new_list();
Node *new_node(char *input) {
Node *new;
new = malloc(sizeof(Node));
new->value = input;
return new;
}
void delete_node(Node *input) {
free(input);
}
void push(List head, char *input) {
if (*head == NULL) {
*head = new_node(input);
}
else {
Node *new = new_node(input);
while ((*head)->next != NULL) {
*head = (*head)->next;
}
(*head)->next = new;
}
}
List new_list() {
List list = malloc(sizeof(List));
*list = NULL;
return list;
}
int main( void ) {
List list = new_list();
push(list, "First!\n");
push(list, "Second!\n");
push(list, "Third!\n");
push(list, "Fourth!");
printf("%s", (*list)->value);
printf("%s", (*list)->next->value);
printf("%s", (*list)->next->next->value); //Segmentation fault
printf("%s", (*list)->next->next->next->value);
return 0;
}
When I ran it with gdb I got the message:
Third!
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400752 in main () at main.c:54
54 printf("%s", (*list)->next->next->value);
typedef struct Node** List;You will want to review: Is it a good idea to typedef pointers?. I can't believe you can't change that. It makes it so much harder to actually learn what is going on when you are hiding pointers behind atypedef.