-2
#include <iostream>
using namespace std;

int main(){
    int a[3], no;
    cout  << "Index Value\n";
    for(int i = 0; i < 100; i++){
        cin >> no;
        a[i] = no;
        cout << i << "\t" << a[i] << endl;
    }
    return 0;
}

Here I initialized a[ 3 ]. In for loop, I'm feeding input 100 times to a[ ], exceeding the indices of [ 3 ].
Why don't it give segmentation error right after when i equals 4.
Input
1 2 3 4 5 6 7
Output
Index Value 0 1 1 2 2 3 4 0 5 5 6 6 7 7
Output is wrong when Index equals 4. Printed 0 . Expected 4

Sparrow
  • 65
  • 2
  • 10
  • 1
    Out of bound indexing is undefined behavior. Search what is undefined behavior and segmentation fault. – P0W Jan 28 '17 at 07:57
  • 2
    UB means anything is possible, it doesn't have to cause a segment fault error. – songyuanyao Jan 28 '17 at 07:59
  • Suppose, if i init a[33] = 120 & print a[33], it prints 120. Where exactly is this a[33] in memory? – Sparrow Jan 28 '17 at 08:01
  • memory error in C++ may be visible, maybe not, maybe later. Thats why words UB are so important – Jacek Cz Jan 28 '17 at 08:03
  • @Sparrow `a[33]` may be located at the Lincoln memorial as far as the standard is concerned, or not exist at all. – Baum mit Augen Jan 28 '17 at 08:04
  • 1
    int a[3] is a local variable and is stored on the stack. When you write beyond element 3 you are writting into unused (but still at a valid address) stack space. A more complex program containing nested calls etc would exhibit strange behaviour. – CascadeCoder Jan 28 '17 at 08:06
  • That's one way it could go, or there may be no stack at all and instead temporary storage is implemented with the breath of drunken walruses. Either would be equally valid in the eyes of the C++ Standard. – user4581301 Jan 28 '17 at 08:58

1 Answers1

1

Unfortunately for the debugging programmer, C and C++ programs don't usually segfault when you write past the end of an array. Instead it will usually silently write over whatever the pointer arithmetic as up to -- if the OS allows it. This often overwrites other variables or even program code, causing confusing and unpredictable errors.

I have used the word "usually" here because according to the standards this is "undefined behaviour" -- that is, the compiler and runtime can do anything they like.

When developing and testing, it can be very useful to use a library such as electricfence, which puts extra checks into memory operations and would make your program fail in the way you expect.

slim
  • 40,215
  • 13
  • 94
  • 127