I have written two small programs in which I declare a very small array.
Then I try to access values out of bounds.
The interesting thing I noticed that when I try to decrement the index I can decrement this very very further away. If I try to increment it the program crashes much faster.
This is my two codes and the results:
#include<stdio.h>
int main()
{
int i=0;
int a[2];
while(1)
{
a[-10000]=8;
printf("i is: %d and the value a[i] is: %d\n",i,a[i]);
i--;
}
return 0;
}
The final lines of the result are:
i is: -3143957 the value of a[i] is: 0 i is: -3143958 the value of a[i] is: 0 i is: -3143959 the value of a[i] is: 0 i is: -3143960 the value of a[i] is: 0 i is: -3143961 the value of a[i] is: 0 i is: -3143962 the value of a[i] is: 0 i is: -3143963 the value of a[i] is: 0 i is: -3143964 the value of a[i] is: 0 Segmentation fault
However when I try to increment the index i
#include<stdio.h>
int main()
{
int i=0;
int a[2];
while(1)
{
a[-10000]=8;
printf("i is: %d and the value a[i] is: %d\n",i,a[i]);
i++;
}
return 0;
}
I get the following result: i is: 2306 and the value a[i] is: 1869098813 i is: 2307 and the value a[i] is: 1764713837 i is: 2308 and the value a[i] is: 1634624869 i is: 2309 and the value a[i] is: 795175011 i is: 2310 and the value a[i] is: 1802724676 i is: 2311 and the value a[i] is: 7368564 i is: 2312 and the value a[i] is: 778121006 i is: 2313 and the value a[i] is: 7632239 i is: 2314 and the value a[i] is: 0 i is: 2315 and the value a[i] is: 0
The difference between how much I can go UP and how much I can go DOWN is HUGE. Why is that.
Some things to mention: I KNOW that this is undefined behavior. My question is strictly about WHY can I go much much further UP vs DOWN when going OUT OF BOUNDS of an array.