Deleting memory in 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 * cur开发者_如何学JAVAr, * 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?
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).
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.
while(head != NULL)
{
item* next = head->next;
free(head);
head = next;
}
精彩评论