Exam C Char Array

I am taking the programming exam the previous year. And I came up with this:

The program (see below) defines two variables x and y.

It produces the given conclusion. Explain why the character "A" appears in the output of the variable x.

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


He has pretty high glasses (7). And I don't know how to explain it in detail. My answer:

The char array (y) only contains 6 characters, so changing the 7th character will change everything after that on the stack.

Any help would be much appreciated! (I'm only 1st year old)

+3


source to share


2 answers


Your official answer should be that this program gives undefined behavior .

The C standard does not define the result of an out-of-bounds access operation.

From char y[6]

, reading or writing to y[7]

, that's exactly what you are doing.

Some compilers may choose to allocate an array x[6]

just after the array y[6]

on the stack.



So, by writing 'A'

to y[7]

, this program can actually write 'A'

to x[1]

.

But the standard does not dictate this, so it depends on the compiler implementation.


Since others have implied previous comments on your question, if this was indeed given in an official exam, then you may want to continue your studies elsewhere ...

+4


source


A classic stack corruption problem in C. Using the debugger, you will find that after the initial jobs, your frame stack looks like this:

67890\012345\0

      

y

points to char 6

. y[7]

means 7 positions after that ( 2

). So, y[7] = 'A'

replaces char 2.



Accessing array access abroad is undefined in the C standard, only one C feature needs to be known. Some references:

+2


source







All Articles