0

I have written a small program but couldn't understand why it does't crash when a is accessed out of bounds?

    #include <iostream>
    using namespace std;
    
    int main()
    {
    
     double *a = new double[4];
    
      a[0]=1;
      a[1]=2;
      a[2]=3;
      a[3]=4;
      cout <<"size of double:"<<sizeof(double)<<endl;
      a[100]=100;  // why is it not crashing here?
    
     return 0;
    }

Could someone explain me whats happening here? Shouldn't this crash at a[100]=100?

Meraj Hussain
  • 329
  • 1
  • 6
  • 24
  • 1
    `a[100]` might or might not be a valid address for your process. It is likely to cause some nasty side effects and will surely cause a crash if the memory does not belong to your process. – Danish Aug 17 '20 at 12:09
  • 2
    A better question is why would it crash? Trying to answer that as an exercise will improve your understanding of c++ memory handling. – Zdeslav Vojkovic Aug 17 '20 at 12:18

1 Answers1

4

Why doesn't the below program crash?

From perspective of C++: Because the behaviour of the program is undefined. The program is neither guaranteed to crash nor to not crash. Nor are there any other guarantees about the behaviour.

From perspective of the operating system: Assuming the compiler did not remove the access due to having detected undefined behaviour, it probably didn't crash because that memory happened to be mapped for the process. In general, it is not safe to assume that all buffer overflows could be detected.

eerorika
  • 232,697
  • 12
  • 197
  • 326