C 庫 - free() 函式



C 的stdlibfree() 函式用於釋放之前由動態記憶體分配函式(如 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.
廣告