C/C++ 中 new/delete 和 malloc/ free 的區別是什麼?


new/ delete

new 運算子要求在堆中分配記憶體。如果記憶體充足,它會將記憶體初始化為指標變數並返回其地址。

delete 運算子用於釋放記憶體。使用者有權透過此 delete 運算子釋放建立的指標變數。

以下是 C++ 語言中 new/delete 運算子的一個示例,

示例

 現場演示

#include <iostream>
using namespace std;

int main () {
   int *ptr1 = NULL;
   ptr1 = new int;
   float *ptr2 = new float(299.121);
   int *ptr3 = new int[28];

   *ptr1 = 28;

   cout << "Value of pointer variable 1 : " << *ptr1 << endl;
   cout << "Value of pointer variable 2 : " << *ptr2 << endl;
   
   if (!ptr3)
   cout << "Allocation of memory failed\n";
   else {
      for (int i = 10; i < 15; i++)
      ptr3[i] = i+1;

      cout << "Value of store in block of memory: ";
      for (int i = 10; i < 15; i++)
      cout << ptr3[i] << " ";
   }
   delete ptr1;
   delete ptr2;
   delete[] ptr3;

   return 0;
}

輸出

以下是輸出

Value of pointer variable 1 : 28
Value of pointer variable 2 : 299.121
Value of store in block of memory: 11 12 13 14 15

malloc/ free

函式 malloc() 用於分配請求的位元組大小,並返回一個指向分配的第一個位元組的指標。如果失敗,它會返回空指標。

函式 free() 用於釋放透過 malloc() 分配的記憶體。它不會改變指標的值,這意味著它仍然指向相同的記憶體位置。

以下是 C 語言中 malloc/free 的一個示例,

示例

 現場演示

#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) malloc(n * sizeof(int));

   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }

   printf("\nEnter elements of array : ");

   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   free(p);

   return 0;
}

輸出

以下是 output −

Enter elements of array : 32 23 21 8
Sum : 84

更新時間:2020 年 6 月 25 日

2K+ 次瀏覽

開啟您的 職業

完成課程後獲得認證

開始
廣告