0
Program:
#include <stdio.h>
main ()
{
    char x[6] = "12345\0";
    char y[6] = "67890\0";
    y[7]='A';
    printf("X: %s\n",x);
    printf("Y: %s\n",y);
}

Program output: X: 1A345 Y: 67890

The following program defines and prints the two variables x and y and gives the above output. Would someone please be able to explain to me why the character A appears in the output of x?

I believe this is due to the way memory is handled in C and writing outside of the bounds of y. I am a computer science student and looking to understand why this happens. Thanks in advance!

Jens
  • 67,715
  • 15
  • 98
  • 113

1 Answers1

1

The memory was probably layed out like this:

6  7  8  9  0 \0 1  2  3  4  5 \0
y                x

And then y[7] is the same as x[1]

Do note that this belongs to the realm of undefined behavior. This means that your code is not required to work that way. Enabling compiler optimizations might change it. When I tried your code in gcc, the behavior went away with -O2 and -O3.

Read more about UB here Undefined, unspecified and implementation-defined behavior

klutt
  • 30,332
  • 17
  • 55
  • 95