Jonah
Jonah

Reputation: 16202

Memory layout and variable declaration order

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¦¦+"

Upvotes: 1

Views: 1277

Answers (1)

rici
rici

Reputation: 241691

Is this behavior specified in C?

No.

Does the compiler always layout the memory in reverse order?

No.

If not, what is the principle he's depending on?

He's not relying on a principle; rather, on the behaviour of particular C compilers. Not all of them will produce the same results. It's undefined behaviour, and so anything (or nothing) could be printed.

Upvotes: 3

Related Questions