free() 函数定义在 stdlib.h 头文件中。它有助于释放使用 calloc、malloc 或 realloc 动态分配的内存。
void free(void *ptr); #where ptr is a memory pointer
free() 函数接受一个参数。如果传入的 ptr 是空指针,则不执行任何操作。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| ptr | 指向先前已分配且需要释放的内存块的指针 | 必需 |
free() 函数不返回任何值。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *s;
/*memory allocation */
s = (char *) malloc(12);
strcpy(s, "programming");
printf("String = %s, Address = %u\n", s, s);
/* Reallocating memory */
s = (char *) realloc(s, 20);
strcat(s, ".com");
printf("String = %s, Address = %u\n", s, s);
free(s);
return(0);
}
输出
String = programming, Address = 355090448 String = programming.com, Address = 355090448
#include <stdio.h>
#include <stdlib.h>
int main (){
int k, * pt, t = 0;
pt = calloc(10, sizeof(int));
if (pt == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Sequence sum of the first 10 terms \ n ");
for (k = 0; k < 10; ++k) { * (pt + k) = k;
sum += * (pt + k);
}
printf("Sum = %d", t);
free(pt);
return 0;
}
输出
Sequence sum of the first 10 terms Sum = 45