So I wrote these two versions of the overloaded assignment operator for an ADT I wrote in class. When I use them in conjunction with my overloaded ostream << operator for that same ADT I see different results. Why? Is it because I deallocated the memory to the other buffer that I am receiving this issue?
void Text::operator= (const Text &other) {
if (this != &other) {
delete [] buffer;
bufferSize = other.bufferSize;
buffer = new char[bufferSize + 1];
strcpy(buffer, other.buffer);
}
}
void Text::operator= (const Text &other) {
if (this != &other) {
delete [] buffer;
bufferSize = other.bufferSize;
buffer = new char[bufferSize + 1];
for (int i = 0; i < bufferSize; i++) {
buffer[i] = other.buffer[i];
}
}
Here is my overloaded ostream <<,
ostream & operator << (ostream &output, const Text &outputText) {
output << outputText.buffer;
return output;
}
The discrepancy occurs like this:
The first one outputs: Hey Jude
The second one outputs: Hey Jude(random garbage)
The second code snippet does not append a terminating null terminator, hence the garbage (
strcpy()copies the terminating null). You need to explicitly add the null terminator after theforloop: