C/C++之动态内存分配比较

Linux大全评论457 views阅读模式

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.   
  4. #include "stdafx.h"   
  5. #include <iostream>   
  6. using namespace std;  
  7.   
  8. class SS  
  9. {  
  10. public:  
  11.     SS();  
  12.     ~SS();  
  13. private:  
  14.     int ff;  
  15.     int gg;  
  16. };  
  17. SS::SS()  
  18. {  
  19.     ff=5;  
  20.     cout << "Constructor called" << endl;  
  21. }  
  22. SS::~SS()  
  23. {  
  24.     cout << "Destructor called" << endl;  
  25. }  
  26. int _tmain(int argc, _TCHAR* argv[])  
  27. {  
  28.     SS *ss;  
  29.     ss = new SS;  // new operator calls constructor.   
  30.     delete ss;    // delete operator calls destructor.   
  31.     return 0;  
  32. }  

运行结果:

C/C++之动态内存分配比较

如图一

 注意:混合用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.   
  4. #include "stdafx.h"   
  5. #include <iostream>   
  6. using namespace std;  
  7.   
  8. typedef struct  
  9. {  
  10.     int ii;  
  11.     double dd;  
  12. } SSS;  
  13.   
  14.   
  15. int _tmain(int argc, _TCHAR* argv[])  
  16. {  
  17. int kk, jj;  
  18. char *str1="This is a text string";  
  19. char *str2 = (char *)malloc(strlen(str1));  
  20.   
  21. SSS *s1 =(SSS *)calloc(4, sizeof(SSS));  
  22. if(s1 == NULL) printf("Error ENOMEM: Insufficient memory available\n");  
  23. strcpy(str2,str1); //Make a copy of the string    
  24. for(kk=0; kk < 5; kk++)    
  25. {  
  26. s1[kk].ii=kk;  
  27. }  
  28. for(jj=0; jj < 5; jj++)  
  29. {  
  30. printf("Value strored: %d\n",s1[jj].ii);  
  31. }  
  32. free(s1);  
  33. free(str1);  
  34. free(str2);  
  35.   
  36. }  

结果:

C/C++之动态内存分配比较

  • malloc: 用于申请一段新的地址
  • calloc: 用于申请N段新的地址
  • realloc: realloc是给一个已经分配了地址的指针重新分配空间
  •   free: 通过指针释放内存

企鹅博客
  • 本文由 发表于 2019年9月8日 21:27:48
  • 转载请务必保留本文链接:https://www.qieseo.com/172518.html

发表评论