-5

What causes a memory leak? And what is the exact definition of the memory leak?

And another question, why does calling getC cause a memory problem?

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;
        }
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 3
    Not using RAII properly and [undefined behaviour](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope). – chris Dec 19 '13 at 01:51
  • 5
    Dynamic allocation using `new[]` must be matched by a `delete[]`, not `delete`. And `getC()` returns a reference to a local variable. – Praetorian Dec 19 '13 at 01:53
  • 1
    A memory leak occurs when someone allocates heap, does not free it, and loses access to the allocation -- ie, loses all pointers to it. – Hot Licks Dec 19 '13 at 01:54

1 Answers1

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;
    }
};
  • Note that getC() returns a pointer to the stack, when another function uses that stack space the contents of c will get overwritten (corrupt)

There is a difference between a memory leak and memory growth - not using delete [] can cause a leak. A leak is when there are no references to allocated memory. Memory growth is often called a leak, but occurs when memory has references but will not be used, for example an allocator that keepss a list of freed memory, but never makes it available for reuse. Since the list exists, it is not a leak, it is memory growth.

Glenn Teitelbaum
  • 10,108
  • 3
  • 36
  • 80