Reputation: 825
When I'm inputting data in curr->data
I first allocate memory by doing curr = (NODE*) malloc (sizeof(NODE));
. Then I build list and eventually at the end, print it. Somewhere in the program I have to free the memory that I've used, but I don't know when to do it. After building the list, or after I print the list? or can I do this?
printf("How many elements do you want to make? ");
scanf("%d", &NumElem);
head = NULL;
for (i = 0; i < NumElem; i++)
{
//memory allocate
curr = (NODE*)malloc(sizeof(NODE));
printf("Number %d: ", i+1);
scanf("%d", &curr->num);
FLUSH;
if (head == NULL)/*beginning of the list*/
{
curr->next = head;
head = curr;
*tail = curr;
}
else /*adding on the list*/
{
curr->next = head;
head = curr;
}
free (curr);
}//for
Can I free each time after I put data inside the current node?
Upvotes: 0
Views: 668
Reputation: 16406
Suppose you're reserved a local meeting room where you plan to have a meeting and then a party. When would you release your reservation ... immediately after you reserved it, after you've had the meeting but before you've had the party, or after you've had both the meeting and the party?
malloc
and free
are like that ... malloc
reserves an area of memory for your use and free
cancels the reservation. If you continue to use the memory after you've cancelled the reservation, the behavior is undefined.
In your case, you need to free your entire list of nodes. You can do that in a loop, but there's a common trap: freeing a node before accessing its next
pointer. The danger is that this almost always works in practice, but it's undefined and sometimes it won't work ... possibly in some software controlling life-critical machinery. Best to learn to do it right now:
void free_list(NODE* list)
{
while (list)
{
NODE* next = list->next;
free(list);
list = next;
}
}
Or in a slightly more compact form,
void free_list(NODE* list)
{
for (NODE* next; list; list = next)
{
next = list->next;
free(list);
}
}
If your node contain pointers to strings or other objects that were malloc
ed and need to be freed, those free calls would be done in free_list before freeing the node itself.
Upvotes: 6