[OCLUG-devel] arrays

Dan Stromberg strombrg at dcs.nac.uci.edu
Sun May 29 13:03:31 PDT 2005


Basically, there is a "contract between the C implementation and the
programmer".

Writing beyond the allocated bounds of an array like this, breaks your
end of the contract (the clause that says "don't reference undefined
regions of memory), which frees the C implementation to no longer hold
up its end of the contract either.  In other words, the C implementation
can do any screwball, random thing it wants in response to this, and
still be perfectly legal C.

However, one of the more likely things that will happen is that a
variable that was allocated after array[5] in the current stack frame
will get trounced, in which case your program may not error out until
much later, for what may seem like a completely unrelated reason.

On Sun, 2005-05-29 at 04:31 -0700, James Colannino wrote:
> Hey everyone.  I have another C question, this time regarding arrays. 
> I'm wondering what would happen if you did the following:
> 
> char array[5];
> 
> for (i = 0; i <= 10; ++i)
>     array[i] = 'a';
> 
> array[11] = '\0';
> 
> /* notice that I've indexed through 7 more than I should have */
> 
> printf ("%s\n", array);
> 
> I know this is NEVER something you should do, but so far, out of
> curiosity (and buggy code :-P), I've gotten away with it every time I've
> tried, and I'm curious what the possible ill effects are.  Thanks in
> advance.
> 
> James
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
Url : http://localhost.localdomain/pipermail/oclug-devel/attachments/20050529/fd3e4bbc/attachment.bin 


More information about the OCLUG-devel mailing list