tags:

views:

131

answers:

4

How do I delete memory in C?

For example, I have:

#include<stdlib.h>
#include<stdio.h>

struct list_el {
   int val;
   struct list_el * next;
};

typedef struct list_el item;

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) {
      printf("%d\n", curr->val);
      curr = curr->next ;
   }
}

After I created the items 1 - 10, how do I delete it and make sure it doesn't exist in memory?

+5  A: 

free() is used to deallocate memory that was allocated with malloc() / calloc(), like so:

curr = head; 

while(curr) {
    item *next = curr->next;
    free(curr);
    curr = next;
}

head = NULL;

(The temporary variable is used because the contents of curr cannot be accessed after it has been freed).

By the way, a better way to write your malloc line in C is:

curr = malloc(sizeof *curr);

(This means that the line remains correct even if the type of curr is changed).

caf
A: 

free() is your friend

GregS
+3  A: 
curr = head;
while (curr != NULL) {
    head = curr->next;
    free (curr);
    curr = head;
}

will do it.

It basically walks curr through the list, deleting as it goes (using head to store the next one) until you've run out of elements.

paxdiablo
Damn, 9 seconds. We were the only ones with code samples, but alas you win.
GMan
@GMan, would you like to explain your "pax cheats" comment in your answer? Are you a five-year-old child?
paxdiablo
Joke on the internet bro-ham. Guess I should have put a smiley.
GMan
No probs, understood now. But the new one is worse :-)
paxdiablo
The new one makes you cool like Master Chief :] http://images.encyclopediadramatica.com/images/d/d4/Halo_kills_aleins.JPG
GMan
A: 
while(head != NULL)
{
  item* next = head->next;
  free(head);
  head = next;
}
Long Cheng