-1

I have a problem with memory allocation in c++. This is my code.

#include <iostream>

using namespace std;

class Animal
{
public:
    Animal(void)
    {

    }

    Animal(int weight):itsWeight(weight)
    {

    }

    ~Animal(void)
    {

    }

    int GetWeight()
    {
        return itsWeight;
    }

    void Display()
    {
        cout << "Weight: " << itsWeight<< endl;
    }
private:
    int itsWeight;
};

class ArrayTemplate
{
public:
    ArrayTemplate(int size)
    {
        animals = new Animal[size];
        index = 0;
    }

    //copy constructor
    ArrayTemplate(const ArrayTemplate &other)
    {

    }

    ~ArrayTemplate(void)
    {
        //if I delete this animals pointer, I got problem.
        delete animals;
    }

    ArrayTemplate operator [] (const Animal &rAnimal)
    {
        animals[index] = rAnimal;
        index++;
        return *this;
    }

    void Display()
    {
        for (int i=0; i<index; i++)
        {
            animals[i].Display();
        }
    }
private:
    //current index.
    int index;
    Animal * animals;
};

int main(int argc, const char * argv[])
{

    ArrayTemplate temp(2);
    Animal animal1(20);
    Animal animal2(30);
    temp[animal1];
    temp[animal2];
    temp.Display();
}

If I delete *animals pointer, I got this error.

cpp_mock_question1(19849,0x7fff7c3be310) malloc: * error for object 0x7fff5fbff8c0: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug

agthumoe
  • 119
  • 1
  • 11

2 Answers2

4

If you allocate something with new[] you should deallocate it with the corresponding delete[]:

delete[] animals;
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
0

ArrayTemplate::operator[] returns by value for some reason, causing a copy to be made. And your copy constructor is empty, so you end up with double frees.

You should write deep-copy code in your copy constructor, and always return *this by reference.

You also need to use delete[], not delete.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055