Deleting memory in C
c
Solution
`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).
Problem
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?