seriously..
I’m an old hacker from the 80’s and with some spare time
on my hands thought I’d ‘C’ what the fuss is about
( my background is Forth, which does things back to front
so I learn a lot about forcing lots of errors )
In this case I’ve set up a small array which I
thought would be 3 elements in size ( 0,1,2 )
If I run the compilation, I would have thought
I’d have got an out-of-bounds error, but no-
it compiles ok and runs sweetly
No great hurry on this one, but it’s
not good for the little bald spot, all that scratchin’.
int main()
{
char members[3][16]; // 3 elements, each 15 char long plus null
printf("\n enter something.. ");
scanf( "%s", members[4]);
printf("\n and something else.. ");
scanf( "%s", members[5]);
printf(" %s ", members[4]);
printf(" %s\n", members[5]);
return 0;
}
C doesn’t do any bounds checking. (Forth doesn’t either, so I’m not sure where the expectation came from.)
Overflowing an array is undefined behavior: it is allowed, but not required, to crash. In this case, the bytes just happen to be in the same virtual memory page as the stack frame where the local variable was placed. If the frame were towards the end of the page, the CPU would recognize a bad address and complain about the overflow.
If you go a few kilobytes or megabytes out, you will likely see something like you expect.