#include <stdlib.h> void free(void *block);
free
frees a block of memory previously allocated by malloc
or
calloc
. block
is a pointer to the memory block.
free
has no return value.
free
call, the page
is returned to the operating system unless the page is included in the
initial heap area whose size can be specified with a run-time argument.
#include <stdio.h> #include <stdlib.h> #include <string.h> struct LIST { struct LIST *next; char text[0]; /* Zero-length arrays are a SAS/C extension. */ }; main(int argc, char *argv[]) { struct LIST *p; struct LIST *q; struct LIST list; char str[256]; int size; while (1){ puts("nBegin new group..."); for (q = &list; ; q = p){ puts("Enter a text string: "); if (fgets(str,sizeof(str),stdin) == NULL){ break; } if (str[0] == '0'){ if (q == &list) exit(EXIT_SUCCESS); break; } size = sizeof(struct LIST) + strlen(str) + 1; p = (struct LIST *)malloc(size); if (p == NULL){ puts("No more memory"); exit(EXIT_FAILURE); } q->next = p; p->next = NULL; strcpy(p->text, str); } puts("nnTEXT LIST..."); /* Be sure to copy the next pointer from */ /* the current block before you free it. */ p = list.next; while(p != NULL){ q = p->next; printf(p->text); free((char *)p); p = q; } list.next = NULL; exit(EXIT_SUCCESS); } }
pfree
Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.