- C 标准库
- C 库 - 首页
- C 库 - <assert.h>
- C 库 - <complex.h>
- C 库 - <ctype.h>
- C 库 - <errno.h>
- C 库 - <fenv.h>
- C 库 - <float.h>
- C 库 - <inttypes.h>
- C 库 - <iso646.h>
- C 库 - <limits.h>
- C 库 - <locale.h>
- C 库 - <math.h>
- C 库 - <setjmp.h>
- C 库 - <signal.h>
- C 库 - <stdalign.h>
- C 库 - <stdarg.h>
- C 库 - <stdbool.h>
- C 库 - <stddef.h>
- C 库 - <stdio.h>
- C 库 - <stdlib.h>
- C 库 - <string.h>
- C 库 - <tgmath.h>
- C 库 - <time.h>
- C 库 - <wctype.h>
- C 标准库资源
- C 库 - 快速指南
- C 库 - 有用资源
- C 库 - 讨论
C 库 - free() 函数
C 的stdlib 库 free() 函数用于释放之前由动态内存分配函数(如 calloc()、malloc() 或 realloc())分配的内存。
此函数通过允许程序员释放不再需要的内存来帮助防止内存泄漏。
语法
以下是 free() 函数的 C 库语法:
void free(void *ptr)
参数
此函数接受一个参数:
-
*ptr - 它表示指向需要释放或解除分配的内存块的指针。
返回值
此函数不返回值。
示例 1
让我们创建一个基本的 c 程序来演示 free() 函数的使用。
#include <stdio.h>
#include <stdlib.h>
int main() {
//allocate the memory
int *ptr = (int*)malloc(sizeof(int));
if (ptr == NULL) {
fprintf(stderr, "Memory allocation failed!\n");
return 1;
}
*ptr = 42;
printf("Value: %d\n", *ptr);
// free the allocated memory
free(ptr);
// Set 'ptr' NULL to avoid the accidental use
ptr = NULL;
return 0;
}
输出
以下是输出:
Value: 42
示例 2
在此示例中,我们动态分配内存,并在分配后使用free()函数释放内存。
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n = 5;
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Check if the memory has been successfully allocated
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated.\n");
// Free the memory
free(ptr);
printf("Memory successfully freed.\n");
}
return 0;
}
输出
以下是输出:
Memory successfully allocated. Memory successfully freed.
广告