1

I always get a garbage value like this 'Íýýýý««««««««îþîþ' at the end when i output my array. What am I doing wrong?

void func()
{
    const int size = 100;
    char * buffer = new char[size];
    for(int i=0; i<size; i++)
        buffer[i] = ' ';

    cout<<buffer;
}

However if I use a for loop to output the buffer, there is no garbage value.

U chaudrhy
  • 401
  • 1
  • 5
  • 16

2 Answers2

8

Because you don't null terminate your buffer, std::cout.operator<<(char*) will try to find \0 as its terminating character.

As pointed out in comments, feel free to append that \0 to the end of your buffer :).

ScarletAmaranth
  • 5,065
  • 2
  • 23
  • 34
0

ScarletAmaranth is right. C style strings (an array of char) must finish with the char '\0'. That's the way functions that play with char arrays (cout in this case) know when the string finish in memory. If you forget the '\0' character at the end of the array, cout prints all the chars in the array and then goes on printing any data in memory after the array. These other data is rubbish, and that's why you see these strange characters.

If you use the string type (more C++ style) instead of char arrays, you won't have this problem because string type don't use '\0' as a string delimiter.

On the other hand, you don't see rubbish when use a loop to iterate over the 100 elements of the array just because you only print these 100 chars. I mean, you control exactly what you are printing and know when to stop, instead of leaving the cout function figure out when to stop printing.

pposca
  • 523
  • 3
  • 10