51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 6598|回复: 2
打印 上一主题 下一主题

[原创] 软件缺陷实验

[复制链接]

该用户从未签到

跳转到指定楼层
1#
发表于 2019-3-29 15:42:21 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
软件缺陷实验:
  1. #include <string.h>
  2. #include <iostream>
  3. using namespace std;

  4. class MyString
  5. {
  6. public:
  7.     char *mChars;
  8.     MyString()
  9.     {
  10.         mChars = new char[strlen("default value")+1];
  11.         strcpy(mChars,"default value");
  12.     }

  13.     MyString& operator=(const MyString& rhs);
  14. };

  15. MyString& MyString::operator =(const MyString& rhs)
  16. {
  17.    /*if(&rhs==this)
  18.         return *this;*/
  19.     if(rhs.mChars != NULL)
  20.     {
  21.         delete []mChars;
  22.         mChars = new char[strlen(rhs.mChars)+1];
  23.         strcpy(mChars,rhs.mChars);
  24.     }
  25.     else
  26.     {
  27.         mChars = NULL;
  28.     }

  29.     return *this;
  30. }

  31. int main()
  32. {
  33.     MyString a;
  34.     cout<<"a.mChars is "<<a.mChars<<endl;
  35.     a=a;
  36.     cout<<"a.mChars is"<<a.mChars<<endl;
  37.     return 0;
  38. }
复制代码


结果截图:

取消注释后:

加上注释后:


断点调试:






在“=”重载操作中,如果涉及指针操作,则必须判断两个对象是否为同一个对象,否则指针*p执行了两次释放操作中,可能会造成死机。
如果在上面的程序中,缺少if(&rhs==this) return *this,则指针将会被释放两次。
今天软件测试课讲得,其实也不是特别理解。当去掉注释的时候,两个a值是一样的,后续弄懂更,先记录一下。。。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

x
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏
回复

使用道具 举报

本版积分规则

关闭

站长推荐上一条 /1 下一条

小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

GMT+8, 2024-5-5 06:06 , Processed in 0.067042 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2024 Comsenz Inc.

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