I\'m reading the C++ Primer Plus by Stephen Prata. He gives this example:
char dog[8] = { \'b\', \'e\', \'a\', \'u\', \'x\', \' \', \'I\', \'I\'}; // not a s
The contents of memory out of bounds is indeterminate. Accessing memory you do not own, even just for reading, leads to undefined behavior.
It looks like your C++ compiler is allocating space in 4-byte chunks, so that every object has an address that is a multiple of 4 (the hex addresses in your dump are divisible by 4). Compilers like to do this because they like to make sure larger datatypes such as int
and float
(4 bytes wide) are aligned to 4-byte boundaries. Compilers like to do this because some kinds of computer hardware take longer to load/move/store unaligned int
and float
values.
In your first example, each array need 8 bytes of memory - a char
fills a single byte - so the compiler allocates exactly 8 bytes. In the second example each array is 3 bytes, so the compiler allocates 4 bytes, fills the first 3 bytes with your data, and leaves the 4th byte unused.
Now in this second case it appears the unused byte was filled with a null which explains why cout
stopped at the end of the string. But as others have pointed out, you cannot depend on unused bytes to be initialized to any particular value, so the behaviour of the program cannot be guaranteed.
If you change your sample arrays to have 4 bytes the program will behave as in the first example.
Its an undefined behaviour, you cannot say what can happen.
Try on some other system you may get different output.
The answer to your question is that it is an Undefined Behaviour and its output cannot be explained.
In addition to above explanantion, in your particular case, you have declared array globally.
Therefore in your second example a \0
is appended in the fourth byte of four-byte boundary as explained by Peter Raynham.
The '\0' is just a solution to tell how long is a string. Lets say you know how long it is by storing a value before the string.
But your case is when you intentionally leave it out the functions and normally your code as well will keep searching for the delimiter ( which is a null character ). It is undefined what is behind the bounds of a specified memory it greatly varies. In Mingw in debug mode with gdb its usually zeroed out, without gdb its just junk... altho this is just my experience. For the locally declared variables they are usually on the stack so what you are reading, is probably your call stack.