Consider this intentionally broken program, modified from Zed Shaw's C tutorial, which creates a char array and leaves of the terminating \0
:
#include <stdio.h>
int main(int argc, char *argv[])
{
char name[] = "Zed";
char full_name[] = {
'Z', 'e', 'd',
' ', 'A', '.', ' ',
'S', 'h', 'a', 'w'
};
printf("name=\"%s\" and full_name=\"%s\"\n", name, full_name);
return 0;
}
The output is:
name="Zed" and full_name="Zed A. ShawZed"
And Zed's comments suggest this output is expected, ie, the memory seems to be laying out full_name
first and then name
, contiguously. Is this behavior specified in C? Does the compiler always layout the memory in reverse order? If not, what is the principle he's depending on?
If we switch the order in which we declare the variables:
char full_name[] = {
'Z', 'e', 'd',
' ', 'A', '.', ' ',
'S', 'h', 'a', 'w'
};
char name[] = "Zed";
Then we get the expected garbage characters at the end of the unterminated char array:
name="Zed" and full_name="Zed A. Shaw4¦h4¦¦+"