Derek W
Derek W

Reputation: 10026

In C++, what is causing the difference between these two functions?

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)

Upvotes: 0

Views: 159

Answers (2)

hmjd
hmjd

Reputation: 121971

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 the for loop:

buffer[bufferSize] = 0;

Upvotes: 6

Luchian Grigore
Luchian Grigore

Reputation: 258618

Little trick:

buffer = new char[bufferSize + 1]();

This:

strcpy(buffer, other.buffer);

also copies the null-terminating character. This:

 for (int i = 0; i < bufferSize; i++) {
     buffer[i] = other.buffer[i];
 }

doesn't, because it's at position bufferSize+1, which you skip.

I'd probably go with iterating to position bufferSize+1 instead of value-initializing the array.

Okay, scrap that, I'd go with using a std::string instead. That way, you don't have to worry about copying, assignment or destruction.

Upvotes: 2

Related Questions