“HEAP CORRUPTION DETECTED”错误原因与解决

“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时候报错。

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值