歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C/C++之動態內存分配比較

C/C++之動態內存分配比較

日期:2017/3/1 11:02:47   编辑:Linux編程

1、C malloc 和 free vs C++ new 和delete:

C 語言的malloc() 和free() 並不會調用析構函數和構造函數。C++的 new 和 delete 操作符 是 "類意識" ,並且當調用new的時候會調用類的構造函數和當delete 調用的時候會調用析構函數。

下面一個例子

  1. // memory.cpp : 定義控制台應用程序的入口點。
  2. //2011/10/13 by wallwind
  3. #include "stdafx.h"
  4. #include <iostream>
  5. using namespace std;
  6. class SS
  7. {
  8. public:
  9. SS();
  10. ~SS();
  11. private:
  12. int ff;
  13. int gg;
  14. };
  15. SS::SS()
  16. {
  17. ff=5;
  18. cout << "Constructor called" << endl;
  19. }
  20. SS::~SS()
  21. {
  22. cout << "Destructor called" << endl;
  23. }
  24. int _tmain(int argc, _TCHAR* argv[])
  25. {
  26. SS *ss;
  27. ss = new SS; // new operator calls constructor.
  28. delete ss; // delete operator calls destructor.
  29. return 0;
  30. }

運行結果:

如圖一

注意:混合用malloc 和delete或者混合用new 和free 是不正確的。C++的new和delete是C++用構造器分配內存,用析構函數清除使用過的內存。

new/delete 優點:

  • new/delete調用 constructor/destructor.Malloc/free 不會.
  • new 不需要類型強制轉換。.Malloc 要對放回的指針強制類型轉換.
  • new/delete操作符可以被重載, malloc/free 不會
  • new 並不會強制要求你計算所需要的內存 ( 不像malloc)

2、C 的動態內存分配:

看如下例子MallocTest.cpp

  1. // memory.cpp : 定義控制台應用程序的入口點。
  2. //2011/10/13 by wallwind
  3. #include "stdafx.h"
  4. #include <iostream>
  5. using namespace std;
  6. typedef struct
  7. {
  8. int ii;
  9. double dd;
  10. } SSS;
  11. int _tmain(int argc, _TCHAR* argv[])
  12. {
  13. int kk, jj;
  14. char *str1="This is a text string";
  15. char *str2 = (char *)malloc(strlen(str1));
  16. SSS *s1 =(SSS *)calloc(4, sizeof(SSS));
  17. if(s1 == NULL) printf("Error ENOMEM: Insufficient memory available\n");
  18. strcpy(str2,str1); //Make a copy of the string
  19. for(kk=0; kk < 5; kk++)
  20. {
  21. s1[kk].ii=kk;
  22. }
  23. for(jj=0; jj < 5; jj++)
  24. {
  25. printf("Value strored: %d\n",s1[jj].ii);
  26. }
  27. free(s1);
  28. free(str1);
  29. free(str2);
  30. }

結果:

圖二

注意:

  • malloc: 用於申請一段新的地址
  • calloc: 用於申請N段新的地址
  • realloc: realloc是給一個已經分配了地址的指針重新分配空間
  • free: 通過指針釋放內存
Copyright © Linux教程網 All Rights Reserved