Reputation: 1
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//defined a data structure "node" which stores an int and a pointer to a node
typedef struct node
{
int number;
struct node *next;
}
node;
//defining functions
node* create(int number);
node* insert(node *new_linked_list, int number);
void print(node *new_linked_list);
void delete_list(node *new_linked_list);
int main(void)
{
//create new linked list with function
node *new_linked_list = NULL;
//get input to update list
for (int i = 0; i < 10; i++)
{
int temp;
if (i == 0)
{
scanf(" %i", &temp);
printf("\n");
new_linked_list = create(temp);
continue;
}
//will insert new nodes in the linked lists
scanf(" %i", &temp);
printf("\n");
new_linked_list = insert(new_linked_list, temp);
}
//prints node number values out
print(new_linked_list);
//delete/free list
delete_list(new_linked_list);
}
//function will return a pointer to the first node in the list
node* create(int number)
{
node *firstnode = malloc(sizeof(node));
firstnode -> number = number;
firstnode -> next = NULL;
return firstnode;
}
//function that will update the linked list and return a pointer to the new head of the linked list
node* insert(node *new_linked_list, int number)
{
node* new_node = malloc(sizeof(node));
if (new_node == NULL)
{
return new_linked_list;
}
//new node will point to the old first node and updates new_nodes number
new_node -> number = number;
new_node -> next = new_linked_list;
//returns a pointer to the new first node
return new_node;
}
void print(node *new_linked_list)
{
//temporary node for reversal
node *trav = new_linked_list;
for (int i = 0; i < 10; i++)
{
printf("%i ",trav -> number);
trav = trav -> next;
if (i == 9)
{
printf("\n");
}
}
}
void delete_list(node *new_linked_list)
{
//base case: at null pointer
if (new_linked_list -> next == NULL)
{
//frees memory previously allocated to a pointer
free(new_linked_list);
return;
}
//else delete the rest of the list
else
{
delete_list(new_linked_list -> next);
}
}
Hi so I was experimenting with a linked list and came across a problem. My program leaks memory because I am not freeing the "new node". However, I'm confused on how to free it as it is being return to be used in main. How would I go about freeing "new node" while still being able to use it in the main function. Thank you for any help in advance.
Upvotes: 0
Views: 48
Reputation: 11
The issue seems to be related to the recursive behaviour of 'delete_list'
It could be implemented like the following:
void delete_list(node *new_linked_list)
{
node *next;
while(new_linked_list != NULL)
{
next = new_linked_list->next;
free(new_linked_list);
new_linked_list = next;
}
}
Upvotes: 1