Memory leak in return

-1

I'm reading a book and I came across this code:

class SimpleCat
{
    public:
    SimpleCat (int age, int weight);
    ~SimpleCat() {}
    int GetAge() { return itsAge; }
    int GetWeight() { return itsWeight; }

    private:
    int itsAge;
    int itsWeight;
};

SimpleCat::SimpleCat(int age, int weight):
itsAge(age), itsWeight(weight) {}

SimpleCat & TheFunction();

int main()
{
    SimpleCat & rCat = TheFunction();
    int age = rCat.GetAge();
    cout << "rCat is " << age << " years old!\n";
    cout << "&rCat: " << &rCat << endl;
    // How do you get rid of that memory?
    SimpleCat * pCat = &rCat;
    delete pCat;
    // Uh oh, rCat now refers to ??
    return 0;
}

SimpleCat &TheFunction()
{
    SimpleCat * pFrisky = new SimpleCat(5,9);
    cout << "pFrisky: " << pFrisky << endl;
    return *pFrisky;
}

My question is:

The book says that there is a memory leak in retun of the SimpleCat & rCat = TheFunction() call due to memory allocation in scope. I wanted to know how to solve this.

    
asked by anonymous 04.01.2017 / 00:37

1 answer

3

The TheFunction function does the following:

SimpleCat * pFrisky = new SimpleCat(5,9);

This line dynamically allocates an instance of class SimpleCat , points its memory address in the variable (pointer) pFrisky and returns that memory address as a reference .

It was already in the main call, the TheFunction function was called like this:

SimpleCat & rCat = TheFunction();

So that dynamically created instance is now being referenced in another address, non-dynamically defined in the rCat variable (which, note, is not a pointer ).

Both calls below print the memory address where the object is located:

  • cout << "pFrisky: " << pFrisky << endl (in function TheFunction )
  • cout << "&rCat: " << &rCat << endl; (in function main )
  • I did not run to be sure, but you'll probably find that they are different addresses (because the second variable, rCat , was not dynamically allocated.

      

    Edit: I performed on Ideone to have   sure, and not necessarily the printed addresses will be   many different. Still, objects are allocated in distinct places   (read about the difference between the heap and the stack right here ), and   this is the leak.

    So when you try to delete that dynamically allocated area by doing:

    SimpleCat * pCat = &rCat;
    delete pCat;
    

    Actually, you're making a beautiful one in a cage ... I mean, silly. :)

    How to solve? If you allocate dynamically, return an even pointer:

    SimpleCat *TheFunction()
    {
        SimpleCat * pFrisky = new SimpleCat(5,9);
        cout << "pFrisky: " << pFrisky << endl;
        return pFrisky;
    }
    

    Then, in main , you do:

    SimpleCat * rCat = TheFunction();
    . . .
    delete rCat;
    
        
    04.01.2017 / 00:54