An example from C traps and pitfalls

An example from Andrew König's book..

From my old blog.


I have been reading Andrew Koenig’s C traps and pitfalls and found an interesting yet simple loop :

#include<stdio.h>
int main()
{
    int i, arr[10];
    for(i=1; i<=10; ++i)
    {
        arr[i]=0;
    }
}

This program will obviously attempt to access arr[10] which does not exist. But that’s a minor thing when compared to its effect on most computers.

If this "runs on a compiler that allocates memory for variables at decreasing addresses, the word after " arr[9] turns out to be i. Because i will be having the largest address, followed by arr[9], arr[8], …, arr[1], arr[0].

So, if you try to access the non-existent arr[10], what’s really being accessed is the memory right after arr[9] which is i.

By setting this value to 0, you are actually resetting the value of i causing the entire loop to start over and loop forever.