Samuel Ricky Samuel Ricky - 1 year ago 61
C Question

Why does the output from printf() change when I write beyond the bounds of another array?

#include <stdio.h>
#include <conio.h>
int main()
char b[] = "samuel ricky";
char c[2];

c[0] = 'd';
c[1] = 'a';
c[2] = 'd';

printf("%s\n", b);

return 0;

If I run this code, the output is:

damuel ricky

And if the code is deleted

c[2] = 'd';

the output is:

samuel ricky

whereas if the code is removed, there is no connection at all with the results output.
How did it happen?

Answer Source

Please enable all your warnings, with the -Wall flag, and you will find the answer in your console:

C02QT2UBFVH6-lm:~ gsamaras$ gcc -Wall main.c 
main.c:10:5: warning: array index 2 is past the end of the array (which contains 2 elements) [-Warray-bounds]
    c[2] =  'd';
    ^ ~
main.c:6:5: note: array 'c' declared here
    char c[2];
1 warning generated.

As the warning says, you write to memory that you don't nescesairily own, since indexing in arrays start from 0, but you seem to already know that.

So char c[2]; has two cells, c[0] and c[1]. Writing to c[2] is invoking Undefined Behavior, which means that what you see printed in your machine now, may be different tomorrow, or at any time in any other machine.

In conclusion, what happens in your machine now is that you are writing 'd' to c[2], which is out of bounds, and it happens to be written in the memory cell of b[0]. That's why you see "damuel ricky" and I, for example, see "samuel ricky".

If I were you, I wouldn't use conio.h, you might end up like Socrates... ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download