2017-01-25 3 views
-2

프로그램을 실행할 때 "Debug Assertion Failed"메시지가있는 창이 나타납니다.오류 디버그 어설 션이 실패했습니다. BLOCK_TYPE_IS_VALID

Source.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; 
} 
+1

문자열과 문자열 :: operator = (String & sir)'strlen (sir.s) +1 '이'this-> s'보다 길 경우 – lcs

+3

3/5/. – Quentin

+0

복사 생성자도 누락되었습니다. '문자열 (const String & sir)'. – PaulMcKenzie

답변

0

그래서이 특정 오류로 이어질 수있는이 코드에 몇 가지 문제가 있습니다. 이 오류는 손상된 메모리를 해제하려고 시도 할 때 발생합니다.

귀하의 경우에는 귀하의 operator==에서 일어나는 것으로 의심됩니다. 이것은 const String& 대신 String을 사용하고 있습니다. 차이점은 String을 입력하면 피연산자의 복사본을 만드는 것입니다. 여기에는 원시 포인터로 사용하는 내부 버퍼에 대한 참조가 포함됩니다. 따라서 그 사본이 범위를 벗어나면 버퍼는 delete[] 에드입니다. 따라서 귀하가 operator+으로 전화를 걸 때까지는 버퍼가 존재하지 않습니다. 그런 다음 런타임은 어설 션 메시지를 통해 정의되지 않은 동작을 경고합니다. 대신 const String&을 전달한 경우 복사본을 만드는 대신 변경할 수없는 매개 변수에 대한 참조를 전달하게됩니다. 이것은 메소드의 끝에서 소멸되지 않고 버퍼가 delete[]이 아닌 것을 보장합니다.

사이드 노트 : 버퍼를 원시 버퍼 대신 std::vector<char>으로 바꾸면 자체 메모리를 관리하고 소멸자가 필요하지 않으므로 더 잘 처리 할 수 ​​있습니다.

관련 문제