巴黎的灯光下 发表于 2019-3-29 15:42:21

软件缺陷实验

软件缺陷实验:
#include <string.h>
#include <iostream>
using namespace std;

class MyString
{
public:
    char *mChars;
    MyString()
    {
      mChars = new char;
      strcpy(mChars,"default value");
    }

    MyString& operator=(const MyString& rhs);
};

MyString& MyString::operator =(const MyString& rhs)
{
   /*if(&rhs==this)
      return *this;*/
    if(rhs.mChars != NULL)
    {
      delete []mChars;
      mChars = new char;
      strcpy(mChars,rhs.mChars);
    }
    else
    {
      mChars = NULL;
    }

    return *this;
}

int main()
{
    MyString a;
    cout<<"a.mChars is "<<a.mChars<<endl;
    a=a;
    cout<<"a.mChars is"<<a.mChars<<endl;
    return 0;
}

结果截图:

取消注释后:

加上注释后:


断点调试:






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

韩初生 发表于 2019-12-31 14:10:17

学习

韩初生 发表于 2019-12-31 14:11:00

学习
页: [1]
查看完整版本: 软件缺陷实验