c++中的delete []异常

昨天一个小学弟写c++程序是出现了一个问题后来经过我们和一个大三的学长讨论解决了这个问题感觉不错,拿出分享他报错这个错
代码如下:`#include
using namespace std;
class Point{
public:
Point();
Point(int x,int y,char * str){
this->x=x;
this->y=y;
//this->str=new char[10];
//strcpy(this->str,”Goods”);
this->str=str;
}

Point(int x,int y){
 this->x=x;
 this->y=y;
 str=new char[10];
 strcpy(str,"Goods");

}
//深拷贝
Point(const Point & point){
  x=point.x;
  y=point.y;
  str=new char[10];
  strcpy(str,point.str);

}
~Point(){

delete [] str;

}
void show();

private:
int x;
int y;
char * str;
};
void Point::show(){

}

int main(){
Point p(3,4);
p.show();
char * str=new char[10];
str=”Goods”;
Point p1(5,6,str);
p1.show();
return 0;

}`

原因出现在这里析构函数中的delete[] 数组 只能删除动态分配的空间,然而我们传入的是保存在文字常量区 的指针,注意虽然main中的str初始化时是指向动态分配的空间但是 str=”Goods”;又变成指向文字常量区 了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值