Output spits two extra control characters, possibly a memory corruption bug?
I have the following program test.cc:
#include <iostream>
unsigned char bogus1[] = {
// Changing # of periods (0x2e) changes output after periods.
0x2e, 0x2e, 0x2e, 0x2e
};
unsigned int bogus2 = 1816; // Changing this value changes output.
int main()
{
std::clog << bogus1;
}
I build it with:
g++ -g -c -o test.o test.cc; g++ -static-libgcc -o test test.o
Using g++ version 3.4.6
I run it through valgrind and nothing is reported wrong.
However the output has two extra control characters and looks like this:
....
That's a control-X and a control-G at the end.
If you change the value of bogus2 you get di开发者_高级运维fferent control characters. If you change the number of periods in the array the issue goes away or changes.
I suspect it is a memory corruption bug in the compiler or iostream package.
What is going on here?
In C/C++, a string is usually stored as a null-terminated char array.
Your unsigned char array isn't null-terminated. Usually it would look something like this:
unsigned char bogus1[] = {
0x2e, 0x2e, 0x2e, 0x2e,
0x00 // terminating NUL byte
};
If it isn't null-terminated, output will continue until a NUL byte is found, that's why it outputs values that are placed in the memory behind your array, like the int bogus2 (which is 0x00000718 in hex, stored in little endian format => 0x18 = Ctrl-X, 0x07 = Ctrl-G, 0x00 ends the output)
You're missing the '\0'
at the end of the string
unsigned char bogus1[] = {
0x2e, 0x2e, 0x2e, 0x2e, 0x00
};
精彩评论