I write a very basic linked list in C supporting only two operations - insert of a node to the top of the list and iterate over the list in order to print the value of each node. The problem I am facing is that I have a segmentation fault when executing. Here is my code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct linkedList
{
int data;
struct linkedList *next;
};
struct linkedList* createNode(int value)
{
struct linkedList *node;
node = malloc(sizeof(struct linkedList));
node->next = malloc(sizeof(struct linkedList));
node->next = NULL;
node = NULL;
return node;
}
//insert a node at the top of the linked list
struct linkedList* insertTop(struct linkedList* top,struct linkedList* node)
{
if(top == NULL)//the element we insert is the 1st element for the linked list
{
node->next = NULL;
//the first element points to NULL since it has no successors
}
else//there is already an element in the list
{
node->next = top;
}
return node;
}
void iterate(struct linkedList* top)
{
while(top->next != NULL)
{
printf("Data = %d\n", top->data);
top = top->next;
}
}
int main()
{
struct linkedList *a,*b,*c,*root;
a = createNode(2);
b = createNode(10);
c = createNode(23);
root = insertTop(NULL,a);//these 3 lines provoke a segmentation fault
root = insertTop(root,b);
root = insertTop(root,c);
iterate(root);//the result I expect here is 23,10,2
return 0;
}
I know this question has been asked many times on stackoverflow and yet I still can't figure out why my code does not work as expected. Can you please explain to me where is the problem and how can I fix it? Thank you
createNode()why are you puttingnode = NULLbefore returning. You are losing the memory that you justmalloced.NULL...createNode()is acutuallycreateMemoryLeak()...