0

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.

snehm
  • 223
  • 3
  • 13
  • 7
    Some people are shooting themselves and are not dying. – Eugene Sh. Oct 16 '17 at 16:08
  • 1
    Yes (to @usr). So in C philosophy we speak "undefined behaviour" and not "error" (in meaning: hard error, exception, example Java, C#, Pascal arrays in safe options). In C result of wrong use MAY occur (or may occur LATER) – Jacek Cz Oct 16 '17 at 16:08
  • 3
    Indexing outside the bounds of an array leads to *undefined behavior*, which doesn't have to result in a segfault. Depending on how the items have been allocated, you may be looking at memory for another variable, or the return address in the stack frame, or padding bytes for alignment purposes, or anything else. – John Bode Oct 16 '17 at 16:11
  • Thank you for clarification. @JohnBode – snehm Oct 16 '17 at 16:52
  • 1
    Also, if you do `int* y = x + 1;` then using `y[-1]` is perfectly fine and equivalent to `x[0]`. – Bo Persson Oct 16 '17 at 18:14

0 Answers0