On Feb 7, 9:54 am, "gallows" <g4ll...@gmail.comwrote:
What is the difference between 'a' and 'b' ? In 'a' I've allocated
space for only a int, why I can use a[1] and a[2]? I tested the code
and seems allright, but I don't understand why.
To put it another way, on top of what all the others have already
said: C doesn't check the bounds of your array accesses (or memory
accesses in general, for that matter).
On my system, this code builds with no warnings, and runs with no
catastrophic errors:
char a='A';
char s[2];
printf("%c\n", a);
s[3] = 'B'; // <-- !!! s[3] is obviously out-of-bounds
printf("%c\n", a);
Should print 'A', 'A', right? On my system, this prints 'A', 'B'
because the out of bounds array access clobbers the value of a.
(Maybe on other systems it prints 'A','A', but the code is still bad.)
(When debugging, things to look for that warn of a buffer overrun in a
local array are variables spontaneously changing value (like in my
example, above), or the program crashing just as the function
returns.)
Sometimes it might make sense to access an array element that leads to
something you haven't allocated, so C allows it. But in this case,
it's not what you want. :-)
-Beej