“HEAP CORRUPTION DETECTED”错误原因与解决
最近遇到一个典型的类的动态内存分配问题,根据网上整理的答案,总结为一般都是操作new申请的内存溢出。
用new申请了一个特定大小的内存,但是后期对这块内存进行复制,可能超过了该内存大小的范围,再进行delete的时候,就会报错。如
char* p=new char[5];
strcpy(p,"aaaaa");
delete[] p;
//Cow.h
#ifndef COW_H
#define COW_H
class Cow
{
char name[20];
char* hobby;
double weight;
public:
Cow();
Cow(const char* nm, const char* bo, double wt);
Cow(const Cow& c);
~Cow();
Cow& operator=(const Cow& c);
void showCow()const;//display all cow data;
};
#endif
//Cow.cpp
#include "Cow.h"
#include <cstring>
#include <iostream>
using namespace std;
Cow::Cow()
{
strcpy(name, "none");
hobby = new char[4];
strcpy(hobby, "cow");
weight = 0.0;
}
Cow::Cow(const char* nm, const char* bo, double wt)
{
strcpy(name, nm);
hobby = new char[strlen(bo) + 1];
strcpy(hobby, bo);
weight = wt;
}
Cow::Cow(const Cow& c)
{
//delete[] hobby;
strcpy(name, c.name);
hobby = new char[strlen(c.hobby) + 1];// 刚开始编译出错 错误 hobby = new char(strlen(c.hobby) + 1)
strcpy(hobby, c.hobby);
weight = c.weight;
}
Cow::~Cow()
{
delete[] hobby;
}
Cow& Cow::operator=(const Cow& c)
{
if (this == &c)
return *this;
else
{
delete[] hobby;
std::strcpy(name, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy(hobby, c.hobby);
weight = c.weight;
return *this;
}
// TODO: 在此处插入 return 语句
}
void Cow::showCow() const
{
std::cout << "Name: " << name << std::endl;
std::cout << "Hobby: " << hobby << std::endl;
std::cout << "Weight: " << weight << std::endl;
}
//usecow.cpp
#include <iostream>
#include "Cow.h"
using namespace std;
int main()
{
Cow cow1;
cow1.showCow();
Cow cow2("yellow","grass",120);
cow2.showCow();
Cow cow3(cow2);
cow3.showCow();
cow1 = cow2;
cow1.showCow();
//system("pause");
return 0;
}
在cow.cpp文件中将hobby = new char[strlen(c.hobby) + 1];/写成了hobby = new char(strlen(c.hobby) + 1),因此实际没有分配合适大小的内存大小,导致在析构函数delete []hobby时候报错。