Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting memory in C

Tags:

c

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?

like image 307
SuperString Avatar asked Jan 20 '10 03:01

SuperString


2 Answers

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).

like image 174
caf Avatar answered Oct 13 '22 03:10

caf


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.

like image 30
paxdiablo Avatar answered Oct 13 '22 01:10

paxdiablo