C庫 - malloc() 函式



C 的stdlibmalloc() 函式用於動態記憶體分配。它分配或預留指定位元組數的記憶體塊,並返回指向已分配空間第一個位元組的指標。

malloc() 函式在編譯時不知道所需記憶體大小,而必須在執行時確定時使用。

語法

以下是 malloc() 函式的C庫語法:

void *malloc(size_t size)

引數

此函式接受單個引數:

  • size_t size − 表示要分配的位元組數。

返回值

以下是返回值:

  • 返回指向新分配的記憶體塊開頭的指標。

  • 如果分配失敗,則返回空指標。

示例1

讓我們建立一個基本的C程式來演示 malloc() 函式的使用。

#include <stdio.h>
#include <stdlib.h>
int main() {
   int *pointer = (int *)calloc(0, 0);
   if (pointer == NULL) {
      printf("Null pointer \n");
   } 
   else {
      printf("Address = %p", (void *)pointer);
   }
   free(pointer);
   return 0;
}

輸出

以下是輸出:

Address = 0x55c6799232a0

示例2

以下是另一個 malloc() 的示例。這裡它用於為包含5個整數的陣列分配記憶體。

#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 using malloc.\n");
   
      // Free the memory
      free(ptr);
      printf("Malloc memory successfully freed.\n");
   }
   return 0;
}

輸出

以下是輸出:

Memory successfully allocated using malloc.
Malloc memory successfully freed.

示例3

下面的C程式將陣列元素動態儲存在指標中,並計算陣列元素的總和。

#include <stdio.h>
#include <stdlib.h>

int main() {
   int n = 5, i, *ptr, sum = 0;
   int arr[] = {10, 20, 30, 40, 50};
   
   ptr = (int*) malloc(n * sizeof(int));
   
   // if memory cannot be allocated
   if(ptr == NULL) {
      printf("Error! memory not allocated.");
      exit(0);
   }
   
   // Copy values from arr to dynamically allocated memory
   for(i = 0; i < n; ++i) {
      *(ptr + i) = arr[i];
      sum += *(ptr + i);
   }   
   printf("Sum = %d", sum);
   
   // free the allocated memory
   free(ptr);
   return 0;
}

輸出

以下是輸出:

Sum = 150
廣告