0

Why is the following code works (printf() gets executed) before i reaches 14? Actually, the execution should fail when i goes past the 10th element of the array, no? Even I I write:

  for(i=0; i<100; i++)

I still get a Segmentation fault of course but all values are printed.

#include <stdio.h>

void funcX() {
    int i;
    int array[10];

    printf("\tEntering funcX()\n");

    //for(i=0; i<11; i++) { //This works
    //for(i=0; i<12; i++) { //This works
    //for(i=0; i<13; i++) { //This works
    for(i=0; i<14; i++) {   //***This fails****
        array[i]=i;
        printf( "array[i]= %d\n", array[i] );
    }

    printf("\tLeaving funcX()\n");
}

int main(int argc, char** argv) {
    printf("Calling funcX() from main()\n");
    funcX();
    printf("Returning from funcX()\n");
    return(0);
}

Compiled on RH Linux using gcc -m32.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
user3772839
  • 265
  • 3
  • 11
  • 2
    Why are you doing this? – haccks Jan 26 '15 at 13:35
  • 1
    It just happens to work. Writing to unallocated memory is undefined behavior. Eventually, you hit a problem and it crashes. You can't rely on it working outside the allocated memory; it's just a fluke based on your machine's current state. – elixenide Jan 26 '15 at 13:35
  • Very similar to [Is accessing a global array outside its bound undefined behavior?](http://stackoverflow.com/q/26426910/1708801) ... your answer is there, the difference is a global array Vs automatic one but essentially the same otherwise. – Shafik Yaghmour Jan 26 '15 at 13:36
  • 1
    Writing out of bounds is not forbidden, but it will lead to [*undefined behavior*](http://en.wikipedia.org/wiki/Undefined_behavior). – Some programmer dude Jan 26 '15 at 13:37
  • You are in undefined behaviour territory!! Please move out of the zone fast! I repeat "Undefined Behaviour" ! - Ok, on a serious note, It is undefined behaviour, it may or may not work. Read this http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior. Maybe you should try compiling with -Wall switch – Suvarna Pattayil Jan 26 '15 at 13:39

1 Answers1

3

on executing

for(i=0; i<14; i++) { 

and for a value of i equal to 10, you're facing undefined behavior by accessing out-of-bound memory [array[i]], the result of which is, well, undefined. One of the side effects is segmentation fault. It is not a must.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261