I have the simplest class text:
class Text
{
char* txt;
public:
Text(const char*);
Text(const Text&);
~Text();
const Text operator+(const Text&) const;
};
and implementation:
#include "text.h"
Text::~Text()
{
delete[] this->txt;
}
Text::Text(const char* argText)
{
txt = new char[strlen(argText)+1];
strcpy(txt, argText);
}
Text::Text(const Text& other)
{
txt = new char[strlen(other.txt)+1];
strcpy(txt, other.txt);
}
const Text Text::operator+(const Text& other) const
{
char* ttxt, *newLine;
ttxt = new char[strlen(txt)+strlen(other.txt)+2];
strcat(ttxt, this->txt);
newLine = new char[2];
newLine[0] = '\n';
newLine[1] = '\0';
strcat(ttxt, newLine);
strcat(ttxt, other.txt);
Text temp(ttxt);
delete[] newLine;
return temp;
}
and main:
#include "text.h"
int main()
{
Text a("First text.");
Text b("Second lol!!\n kthxbye!!!!!!!");
Text c(a+b);
}
and the program breaks on newLine = new char[2]; I tried increasing it, like new char[5] but still it breaks. The message I recieve is:
Windows has triggered a breakpoint in prTextClass.exe.
This may be due to a corruption of the heap, which indicates a bug in
prTextClass.exe or any of the DLLs it has loaded…
Note that
ttxt = new char[strlen(txt)+strlen(other.txt)+2];does not initialize the array content. Thus, whenstrcat()is called, it goes throughttxtto find the first'\0'character as the end of stringttxtand thus stopped at an unknown position.You should change it into