visual C++内存分配错误

visual C++ memory allocation error

本文关键字:错误 分配 内存 C++ visual      更新时间:2023-10-16

我在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_lock_question1(19849,0x7fff7c3be310)malloc:*对象0x7fff5fbff8c0的错误:未分配释放的指针*在malloc_error_break中设置断点以调试

如果用new[]分配某个东西,则应该用相应的delete[]:解除分配

delete[] animals;
由于某种原因,

ArrayTemplate::operator[]按值返回,导致生成副本。并且您的复制构造函数是空的,所以您最终会得到两次释放。

您应该在复制构造函数中编写深度复制代码,并始终通过引用返回*this

您还需要使用delete[],而不是delete