CRT detected that the application wrote to memory after end of heap buffer 오류 해결

jwkim0911의 이미지

해당 코드를 실행하게 되면 중단점 명령 실행됨이라는 오류가 발생하게 됩니다. 이것이 정확히 무엇을 의미하고 어떠한 방식으로 해결할 수 있는지 궁금합니다. 또한 CRT detected that the application wrote to memory after end of heap buffer 라는 오류 화면 또한 볼 수 있었습니다.

#pragma warning(disable:4996)
#include <iostream>
#include <cstring>
using namespace std;
 
class String
{
private:
	char* a;
public:
	String(const char *C=" ")
	{
	    a = new char[strlen(C) + 1];
		strcpy(a, C);
	}
	String(const String& copy)
	{
		a = new char[strlen(copy.a) + 1];
		strcpy(a, copy.a);
	}
	~String()
	{
		delete []a;
	}
	friend String operator+(String a,String b);
	void showfun() const;
};
 
 
String operator+(String X,String Y)
{
	String res(strcat(X.a , Y.a));
	return res;
}
 
void String::showfun() const
{
	cout << a << endl;
}
 
int main()
{
	String a("Happy");
	String b(" BirthDay");
	String d;
 
	(a + b).showfun();
	return 0;
}

ymir의 이미지

String operator+(String X,String Y)
{
	String res(strcat(X.a , Y.a));
	return res;
}

위 코드에서 String X 의 a 는 이미 주어진 문자열("Happy") 크기 만큼의 공간만을 할당받은 상태인데, 그 뒷부분에 데이터를 더 이어붙이려고 하면.. 유효하지 않은 공간에 데이터를 쓰게 되는 셈이 되겠죠.

되면 한다! / feel no sorrow, feel no pain, feel no hurt, there's nothing gained.. only love will then remain.. 『 Mizz 』