c++中的delete []异常
2016-04-05 15:09
369 查看
昨天一个小学弟写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;
}
delete [] str;
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”;又变成指向文字常量区 了
代码如下:`#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”;又变成指向文字常量区 了
相关文章推荐
- C++内存分配及变长数组的动态分配
- C++输入数据流用回车符判断终止
- 蓝桥杯b组c++.6
- knn的c++版本
- C++正则表达式匹配器
- C语言中数组与指针
- C/C++程序题(26-30)
- c++复习:C++的精髓—虚函数virtual用法白话详解
- 五位数倒序
- Youki的C++命名规则
- 关于C++中的友元函数的总结
- C++ 简洁打印 N阶螺旋矩阵
- C++内存分配方式
- C++接口定义及实现举例
- C++学习之旅get、getline的用法
- vc++ 6.0编译后生成的文件
- Google C++ 编程风格指南
- C++多态的本质
- 运维调试记录:C++ compile error: default argument given for parameter
- c++ 逗号操作符重载