1

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?

ChaseTheSun
  • 3,810
  • 3
  • 18
  • 16
  • I think the memory is freed at the end of the program since once a process is terminated all its structures and memory locations should be freed. – smellyarmpits May 12 '13 at 13:22

1 Answers1

1

Is the malloc'd memory automatically free'd at the end of the program?

No, it is not freed 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
   }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523