C++内存泄露(Memory Leak Faults)之高级篇

来源:互联网 发布:教师培训挂机软件 编辑:程序博客网 时间:2024/06/06 19:02

http://blog.csdn.net/acb0y/article/details/6211335

C++内存泄露(Memory Leak Faults)之高级篇

       如果在构造函数中有申请内存的操作,且在其他程序中有两个对象直接或间接的赋值操作,如果没有对“=”运算符进行重载定义,则会产生两次释放同一次内存操作的错误。该错误为第7类的内存错误。

Demo代码如下:

[cpp] view plaincopyprint?
  1. /* 
  2.     FileName: MemoryLeakFault2.cpp 
  3.     Author: ACb0y 
  4.     Create Time: 2011年2月27日14:22:11 
  5.     Last modify Time: 2011年2月27日15:05:39 
  6.  */  
  7. #include <iostream>   
  8. using namespace std;  
  9. #define TEST   
  10.   
  11. /* 
  12.     测试基类 
  13.  */  
  14. class base   
  15. {  
  16. public:  
  17.     char * strName;  
  18.     base(char *);   
  19.     base(const base &);  
  20.     ~base();  
  21. #ifdef TEST   
  22.     base & operator = (const base &);  
  23. #endif   
  24. };  
  25.   
  26. /* 
  27.     构造函数,在构造函数里有动态申请空年。 
  28.  */  
  29. base::base(char * str)   
  30. {  
  31.     strName = new char[strlen(str) + 1];  
  32.     strcpy(strName, str);  
  33. }  
  34.   
  35. //拷贝构造函数   
  36. base::base(const base & r)   
  37. {  
  38.     strName = new char[strlen(r.strName) + 1];  
  39.     strcpy(strName, r.strName);  
  40. }  
  41.   
  42. /* 
  43.     析构函数,释放空间 
  44.  */  
  45. base::~base()  
  46. {  
  47.     if (NULL == strName)   
  48.     {  
  49.         return ;  
  50.     }  
  51.     else   
  52.     {  
  53.         cout << "释放的空间地址为:" << (int)strName << endl;  
  54.         delete [] strName;  
  55.     }  
  56. }  
  57.   
  58.   
  59. #ifdef TEST   
  60. /* 
  61.     赋值运算符。 
  62.  */  
  63. base & base::operator = (base const & r)   
  64. {  
  65.     if (this == &r)   
  66.     {  
  67.         cout << "the same object" << endl;  
  68.     }  
  69.     else   
  70.     {  
  71.         if (NULL != this->strName)  
  72.         {  
  73.             delete [] this->strName;  
  74.         }  
  75.         this->strName = new char[strlen(r.strName) + 1];  
  76.         strcpy(this->strName, r.strName);  
  77.     }  
  78.     return *this;  
  79. }  
  80. #endif   
  81.   
  82. int main()  
  83. {  
  84.     base a("base_a");  
  85.     base b("base_b");  
  86.     a = b;  
  87.     return 0;   
  88. }  

运行结果如下:

      但把,程序开头部分的#define TEST你运行结果会发现,统一地址的空间被释放了两次。从而发生内存泄露。

 

原创粉丝点击