I'm looking at:
http://www.macs.hw.ac.uk/~rjp/Coursewww/Cwww/linklist.html
and notice free
isn't called at the end of the program for each linked list item.
Question: Is the malloc
'd memory automatically free
'd at the end of the program?
I'm looking at:
http://www.macs.hw.ac.uk/~rjp/Coursewww/Cwww/linklist.html
and notice free
isn't called at the end of the program for each linked list item.
Question: Is the malloc
'd memory automatically free
'd at the end of the program?
Is the malloc'd memory automatically
free
'd at the end of the program?
No, it is not free
d in the C sense of the word. It is returned back to the operating system when the program finishes, but unless you call a free
explicitly, it's a memory leak.
You can fix the memory leak as follows:
void main() {
item * curr, * head;
int i;
head = NULL;
for(i=1;i<=10;i++) {
curr = (item *)malloc(sizeof(item));
curr->val = i;
curr->next = head;
head = curr;
}
curr = head;
while(curr) {
void *toFree = curr;
printf("%d\n", curr->val);
curr = curr->next ;
free(toFree); // <<<== Add this
}
}