【问题标题】:Error Debug Assertion Failed. BLOCK_TYPE_IS_VALID错误调试断言失败。 BLOCK_TYPE_IS_VALID
【发布时间】:2017-01-25 15:12:02
【问题描述】:

当我运行我的程序时,会出现一个带有“Debug Assertion Failed”消息的窗口。

源.cpp

#include <iostream>
#include "Header.h"

using namespace std;    
String :: String ()    
{    
    this->s=new char[50];
}

String :: String(char *sir)    
{    
    this->s=new char[strlen(sir)+1];
    strcpy_s(this->s, strlen(sir)+1, sir);
}

String :: ~String()    
{    
    delete [] s;
}

String& String:: operator=(String &sir)    
{       
    strcpy_s(this->s, strlen(sir.s)+1, sir.s);
    return *this;

}

String String:: operator+(String sir)    
{    
    String rez;
    rez.s=new char [strlen(s)+strlen(sir.s)+1];
    strcpy_s(rez.s, strlen(s)+1,s);
    strcat_s(rez.s, strlen(s)+strlen(sir.s)+1, sir.s);
    return rez;

}

void String:: afisare()    
{    
    cout << s<< endl;
}

bool String:: operator==(String sir)    
{    
    if(strcmp(s, sir.s)==0)
        return true;
    else
        return false;
}`

Main.cpp

#include <iostream>    
#include "Header.h"

using namespace std;

int main()    
{
    String sir1("John ");
    String sir2("Ola ");
    String rez;
    if(sir1==sir2)
        cout << "string are identicaly"<< endl;
    else
        cout << "strings are not identicaly"<< endl;

    rez=sir1+sir2; // this line i have debug assertion failed
    rez.afisare();
    return 0;
}

【问题讨论】:

  • String&amp; String:: operator=(String &amp;sir)strlen(sir.s)+1 长于this-&gt;s 时会发生什么
  • 了解三/五/零规则
  • 您还缺少复制构造函数。 String(const String &amp;sir).
  • 在使用符号 String 和使用 using namespace std; 时要非常小心,实际上我建议将 using 全部去掉。
  • 好东西std::string 是小写的。会不会有冲突??

标签: c++ string oop assertions


【解决方案1】:

因此,此代码中存在一些可能导致此特定错误的问题。当您尝试释放已损坏的内存时会发生此错误。

我怀疑你的情况是在你的operator== 中发生的。这是采用String 而不是const String&amp;。不同之处在于,通过接收String,您正在制作操作数的副本。这包括对您故事中的内部缓冲区的引用作为原始指针。因此,当该副本超出范围时,该缓冲区将被delete[]ed。因此,当您尝试调用 operator+ 时,缓冲区不存在。然后,运行时通过断言消息提醒您未定义的行为。相反,如果您传入const String&amp;,您将传入对无法更改的参数的引用,而不是进行复制。这将确保它在方法结束时不会被破坏,并且缓冲区不是delete[]ed。

旁注:如果您将缓冲区切换为 std::vector&lt;char&gt; 而不是原始缓冲区,那么您最好使用它来管理自己的内存,并且您不需要析构函数。

【讨论】:

    猜你喜欢
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 2011-12-08
    • 2015-06-27
    相关资源
    最近更新 更多