I have been trying to free the allocated memory of a file loaded into a linked list, I have managed to free the nodes, but I can't figure out how to free the allocated memory of the file's values copies.
I have tried something like that:
void FreeString(struct node * newNode)
{
for (int i = 0; i < 5; i++)
{
free(newNode->string);
}
}
but the compiler would crash with a segmentation fault, and valgrind would still point out to memory leaks.
it would be appreciated if anyone can tell me what am I doing wrong, and point me to the right direction.
Full code:
The struct:
typedef struct node
{
char *string;
struct node *next;
}node;
// main function here...
void Push(struct node **RefHead, char *word)
{
struct node *newNode = NULL;
newNode = (struct node *)malloc(sizeof(node));
newNode->string = (char*)malloc(strlen(word) + 1); // can't free this part here
strcpy(newNode->string, word);
newNode->next = *RefHead;
*RefHead = newNode;
}
Loading the file into memory:
void FileToNode()
{
struct node *head = NULL, *current = NULL;
infile = fopen("file.txt", "r");
if (infile == NULL)
{
printf("Could not open file\n");
exit(1);
}
while (fgets(word, sizeof(word), infile))
{
Push(&head, word);
}
fclose(infile);
current = head;
while(current)
{
printf("%s", current->string);
current = current->next;
}
freeAll(head);
}
The Free function:
void freeAll(struct node *head)
{
struct node *current = NULL;
while ((current = head) != NULL)
{
head = head->next;
free(current);
}
}