VC驿站

 找回密码
 加入驿站

QQ登录

只需一步,快速开始

搜索
查看: 802|回复: 2

delete重复释放同一块内存报错要怎么修改呀(除了不用指针)#36课后小作业

[复制链接]
89_avatar_middle
最佳答案
0 
在线会员 发表于 2021-12-17 17:07:28 | 显示全部楼层 |阅读模式
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;

  4. class CStudent
  5. {
  6.         char* p_name;
  7.         char sex;
  8.         int id;
  9.         int age;

  10. public:
  11.         CStudent() {};
  12.         CStudent(const char* t_name, char t_sex, int t_id, int t_age):sex(t_sex), id(t_id), age(t_age)
  13.         {
  14.                 int len_p = strlen(t_name);
  15.                 p_name = new char[len_p + 1];
  16.                 memset(p_name, 0, len_p);
  17.                 strcpy(p_name, t_name);
  18.         }
  19.         ~CStudent()
  20.         {
  21.                 cout << "Student " << *p_name << "\t has been deleted!" << endl;

  22.                 if (p_name!= NULL)
  23.                 {
  24.                         delete[]p_name;
  25.                         p_name = NULL;
  26.                 }
  27.         }
  28. };


  29. void test()
  30. {
  31.         CStudent stud_1("zhangsan", 'f', 1001, 20);
  32.         CStudent stud_2;
  33.         stud_2 = stud_1;
  34. }

  35. int main()
  36. {
  37.         test();
  38.         return 0;
  39. }
复制代码




上一篇:分享,学习历程,求大家在编程思路上多指导。。。
下一篇:mfc 非模态窗口
20_avatar_middle
最佳答案
1 
在线会员 发表于 2021-12-20 15:01:58 | 显示全部楼层
stud_2 = stud_1; 这条语句错了,这样写会导致,stud_2.p_name =stud_1.p_name。然后stud_1析构的时候stud_1.p_name对应的内存被删除了,等到stud_2析构时,stud_2.p_name != NULL,然后调用delete,但是这块内存已经在stud_1析构时已经delete了,所以会报错。
如果一定要stud_2 = stud_1这样写,请重载 =,具体请看重载课程。
或者在test函数内这样写。
void test()
{
        CStudent stud_1("zhangsan", 'f', 1001, 20);
        CStudent stud_2;
        stud_2 = stud_1;

        int len = strlen(stud_1.p_name);               ///计算stud_1.p_name长度
        stud_2.p_name = new char[len + 1]{0};   ///为stud_2.p_name申请内存
        strcpy(stud_2.p_name, stud_1.p_name);  ///为stud_2.p_name复制内容
}
89_avatar_middle
最佳答案
0 
ico_lz  楼主| 发表于 2022-1-5 16:30:36 | 显示全部楼层
zhengl33 发表于 2021-12-20 15:01
stud_2 = stud_1; 这条语句错了,这样写会导致,stud_2.p_name =stud_1.p_name。然后stud_1析构的时候stud ...

谢谢!看来是需要进行运算符重载
您需要登录后才可以回帖 登录 | 加入驿站 qq_login

本版积分规则

×【发帖 友情提示】
1、请回复有意义的内容,请勿恶意灌水;
2、纯数字、字母、表情等无意义的内容系统将自动删除;
3、若正常回复后帖子被自动删除,为系统误删的情况,请重新回复其他正常内容或等待管理员审核通过后会自动发布;
4、感谢您对VC驿站一如既往的支持,谢谢合作!

关闭

站长提醒上一条 /2 下一条

QQ|小黑屋|手机版|VC驿站 ( 辽ICP备09019393号-4 )|网站地图wx_jqr

GMT+8, 2023-12-10 10:04

Powered by CcTry.CoM

© 2009-2021 cctry.com

快速回复 返回顶部 返回列表