什么导致C ++中的内存泄漏?

时间:2013-12-19 01:51:18

标签: c++ memory-leaks

导致内存泄漏的原因是什么?什么是内存泄漏的确切定义?

还有一个问题,为什么调用getC会导致内存问题?

class C
{
    public:
       C(int k) : arrSize(k)
       {
           arr = new int[k];
       }
       ~C()
       {
           delete arr;
       }

    private:
        int arrSize;
        int *arr;
};

class B
{
    public:
        C& getC()
        {
            C c(8);
            return c;
        }
};

1 个答案:

答案 0 :(得分:2)

class C
{
public:
   C(int k) : arrSize(k)
   {
     arr = new int[k];
   }
   C(const C&);                // you need to add this (Lookup: Rule of 3)
   C& operator=(const C&);     // you need to add this (Lookup: Rule of 3)
   ~C()                        // this is 1 of the Rule of 3, so you need all 3
   {
     delete arr;               // this needed to be: delete [] arr;
   }                           // since you did a new [] in the constructor
private:
   int arrSize;
   int *arr;
};
class B
{
public:
    C& getC()
    { 
       C c(8);               // * see Note
       return c;
    }
};
  • 请注意,getC()返回指向堆栈的指针,当另一个函数使用该堆栈空间时,c的内容将被覆盖(损坏)

内存泄漏与内存增长之间存在差异 - 不使用delete []会导致泄漏。泄漏是指没有对已分配内存的引用。内存增长通常称为泄漏,但是在内存具有引用但不会被使用时发生,例如,保留已释放内存列表的分配器,但永远不会使其可用于重用。由于列表存在,它不是泄漏,而是内存增长。