Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Exam Char Array

Tags:

arrays

c

char

I am doing previous year C programming exam. And I came up with this:

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

It produces the given output. Explain why the character ‘A’ appears in the output of 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


It has pretty high points (7). And I don't know how to explain it in detail. My answer would be:

char array (y) only have 6 chars allocated so changing 7th character will change whatever is after that in stack.

Any help would highly appreciated! (I'm only 1st year)

like image 480
PiDEV Avatar asked Nov 23 '25 05:11

PiDEV


2 Answers

Your formal answer should be that this program yields undefined behavior.

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

With char y[6], by reading from or writing into y[7], this is exactly what you are doing.

Some compilers may choose to allocate array x[6] immediate after array y[6] in the stack.

So by writing 'A' into y[7], this program might indeed write 'A' into x[1].

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


As others have implied on previous comments to your question, if it was really given on a formal exam, then you may want to consider continuing your studies elsewhere...

like image 163
barak manos Avatar answered Nov 24 '25 22:11

barak manos


The classic stack corruption problem in C. With the help of a debugger, you will find that your frame stack will look like this after the original assignments:

67890\012345\0

y points to the char 6. y[7] means 7 positions after that (2). So y[7] = 'A' replaces the char 2.

Access array beyond bound is undefined in the C standard, just one more quirk of C to be aware of. Some references:

  • Understanding stack corruption
  • Why do compilers not warn about out-of-bounds static array indices?
like image 42
Code Different Avatar answered Nov 24 '25 22:11

Code Different