I'm working on a C program that includes sophisticated memory allocation and dynamic data structures, and I'm getting a segmentation error that's been bothering me for a long, so I read this article but couldn't go very far. Can someone assist me? Here's a condensed version of my code:
Code:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct LinkedList {
struct Node* head;
};
void initializeLinkedList(struct LinkedList* list) {
list->head = NULL;
}
void insertNode(struct LinkedList* list, int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = list->head;
list->head = newNode;
}
void displayList(struct LinkedList* list) {
struct Node* current = list->head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main() {
struct LinkedList myList;
initializeLinkedList(&myList);
insertNode(&myList, 10);
insertNode(&myList, 20);
insertNode(&myList, 30);
displayList(&myList);
return 0;
}
When I execute the program, I get a segmentation fault. The code is meant to generate a linked list and show its contents, but something is obviously incorrect. I assume it has something to do with memory allocation, but I'm having problems identifying the problem. Can you assist me in identifying the issue and suggesting a solution?