簡體   English   中英

C ++內存分配錯誤

[英]C++ memory allocation error

我在C ++中有內存分配問題。 這是我的代碼。

#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();
}

如果刪除* animals指針,則會出現此錯誤。

cpp_mock_question1(19849,0x7fff7c3be310)malloc: *對象0x7fff5fbff8c0錯誤:未分配釋放的指針*在malloc_error_break中設置斷點以進行調試

如果使用new[]分配內容,則應使用相應的delete[]取消分配內容:

delete[] animals;

ArrayTemplate::operator[]由於某種原因按值返回,從而導致進行復制。 而且您的副本構造函數為空,因此最終會獲得兩次釋放。

您應該在復制構造函數中編寫深層復制代碼,並始終通過引用返回*this

您還需要使用delete[]而不是delete

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM