[OCLUG-devel] arrays

Christopher Smith x at xman.org
Sun May 29 09:22:44 PDT 2005


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.
>  
>
C doesn't have any bounds checking so it's not going to stop you from 
accessing data outside the array. Now, depending on how the allocator is 
setup, there may be some "padding" around your array that prevents 
really bad things from happening. In terms of what could go wrong? Well, 
this is a classic example of how stack overflows occur. You're writing 
past the end of the stack-allocated array, which means you're writing 
all over the stack. I'm guessing you aren't having a problem because 
you're exiting immediately after this. However, if this was in a 
subroutine, then when you return, the subroutine would pop off the 5 
bytes of your array and any arguments that were passed in, and then pop 
off the return address. If the return address has been overwritten by 
your array data, then it'll jump somewhere unanticipated. In most cases 
this will be a segmentation fault because it'll be a totally invalid 
address (which should be happening in this case). Sometimes though, you 
can be unfortunate enough to write in an address that is valid, at which 
your program will jump to that location and attempt to execute 
instructions. Very, very messy.

--Chris


More information about the OCLUG-devel mailing list