visual C++内存分配错误
visual 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_lock_question1(19849,0x7fff7c3be310)malloc:*对象0x7fff5fbff8c0的错误:未分配释放的指针*在malloc_error_break中设置断点以调试
如果用new[]
分配某个东西,则应该用相应的delete[]
:解除分配
delete[] animals;
ArrayTemplate::operator[]
按值返回,导致生成副本。并且您的复制构造函数是空的,所以您最终会得到两次释放。
您应该在复制构造函数中编写深度复制代码,并始终通过引用返回*this
。
您还需要使用delete[]
,而不是delete
。
相关文章:
- vector.resize()中的分配错误
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- 如何修复只读对象中成员的错误分配?
- 无法将错误分配给成员函数中"类型的实体"
- 分段错误分配函数结果
- 如何实现,错误分配中止而不是抛出异常
- C++代码错误分配
- 如何修复错误分配C++运行时错误
- 分段错误 - 分配类困难
- 带有数组类型表达式的错误分配
- Sprintf 缓冲区问题,错误分配给字符数组
- 而 (p=strtok(NULL, "," )) 警告:p可识别的错误分配
- 错误:分配只读位置“arr2.IntArray::operator[](1)”arr2[1]=24;
- std::映射错误分配错误
- 为什么"e.what()"打印"错误分配"?
- std::vector<const char *>的错误分配效果?
- 使用指向类的指针进行错误分配
- 错误:分配只读引用“__b”
- 向量错误分配错误 C++