Here is the program,
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[] = {1,2,3,4}; //static array
int *x = (int*)malloc(5*sizeof(int)); //dynamic array
printf("a[-1] - > %d", a[-1]);
printf("x[-1] -> %d", x[-1]);
//printf("a[-31924] -> %d", a[-31924]);
/*this will give segmentation fault, but no segmentation fault from -1 to -31923 */
//printf("x[-5] -> %d", x[-5]);
/*this will give segmentation fault, but no segmentation fault till -1 to -4 */
return 0;
}
Above program will work correctly and will print two garbage value. I have been writing code in C from last 2 years, but this is something new (actully strange) for me.
I dont know how this is working for -ve index value, it should have gave me some runtime error (segmentation fault) for accessing memory that is not allocated to the program? (this is my observation till now)
How memory is allocated in C, does it allocate some extra memory at the two ends of array or what?
when does segmentation fault actully occur?
I kow this question has been already asked several times, but I want to know with respect to this program.
Also note array when statically allocated do not give segmentation fault for negative values upto -31923, and array allocated dynamically do not give segmentation fault for -ve values upto -5. This is something related to stack and heap, but please can anyone explain.