Friday, October 24, 2008

I know this code does not work as expected

Well I came across this amazing piece of code which does not crash as expected.

#include <stdio.h>
#include <stdlib.h>

int main()
    int i;
    int array[4];
    for(i=0; i<=8; i++)

  return 0;

This seems to be perfectly ok code. Obviously it falters at the point where I set value to the array at index 4 - 8. Everyone would generally expect it to crash, but amazingly it did not. I tried it on wxDevcpp and it runs in an infinite loop. I was amazed at why it did. Its interesting to know what happened.

Let me first explain what actually happened. Casual observation revealed that the for loop runs forever. It seems that value of i is reset to 1 each time it reaches 7. Wow this is amazing. But what happened.

What happened is simple. Our incorrect program overwrites 'i' when it tries to put zero at array[7]. That because &array[7] is same as &i. Why? well thats because our amazing manner in which local variables are stored in the stack. So what happens is i  is there in the stack some place above array and we happen it make is zero each time.

Amazing simple reason why this kind of crappy thing happens.