
- 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 程式設計資源
- 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.
廣告