I’m writing a small program that prints a linked list. This list contains a string and a pointer to the next node.
I pass the linked list to a function that adds a new node and fills data field.
When I get back to main function and try to print the list content I get segmentation fault error, although from the function add_node I can print the content of the node.
I want to be able to pass a list and a string to a function and the function must add a new node to the list with the string I passed.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char filename[25];
struct node *next;
};
typedef struct node LISTNODE;
typedef LISTNODE *LISTNODEPTR;
void add_node(LISTNODEPTR *nFile, char *chaData);
int main (int argc, char *argv[])
{
LISTNODEPTR nFile = NULL;
printf("Printing list\n");
add_node(&nFile, "file.txt");
printf("%s\n", nFile->filename);
free(nFile);
return 0;
}
void add_node(LISTNODEPTR *nFile, char *chaData)
{
LISTNODEPTR head = *nFile;
LISTNODEPTR newNode;
newNode = (LISTNODEPTR) malloc(sizeof (struct node));
strcpy(newNode->filename, chaData);
printf("%s\n", newNode->filename);
newNode->next = head; //link next. newNode next points to head (beginning of the list). At this time (head & newNode)->2nd->3rd->NULL
head = newNode;
}
Output:
Printing list
file.txt
Segmentation fault
OS:
Linux sisdvb02 2.6.35-28-server #49-Ubuntu SMP Tue Mar 1 14:55:37 UTC 2011 x86_64 GNU/Linux
Compiler: gcc -Wall -o list list.c
nFilein youradd_node()function does not change. It still points toNULLand since you try to dereference aNULLyou get a segmentation violation error. Btw, use Valgrind to help you with such problems.Change your function to something like this: