-4

I was testing the new operator in C++ as the following:

#include <iostream>
using namespace std;


int main()
{

int *Q = new int[5];

Q[0] = 0;
Q[1] = 1;
Q[2] = 2;
Q[3] = 3;
Q[4] = 4;


for (int i = 0; i < 7; i++)
    {
        cout << "Q[" << i << "] = " << Q[i] << endl;
    }
return 0;
}

If you notice, in the for loop I am exceeding the limit of the pointer and I was expecting an stack over flow type of error; but instead of that it just printed what ever these two extra locations have.

Does any one have explanation about this ?

Anas
  • 359
  • 1
  • 5
  • 14
  • 3
    Undefined behavior is undefined; anything or nothing can happen. – 5gon12eder Feb 14 '15 at 13:09
  • 2
    It is just undefined behaviour. You can't expect any particular outcome from running this program. – juanchopanza Feb 14 '15 at 13:09
  • I understand that this program does nothing (it is meant to be a test program for the "new" operator). However, if I write the same program in C using the malloc operator I get an overflow error when trying to access Q[5] and Q[6]. – Anas Feb 14 '15 at 13:12
  • 1
    possible duplicate of [Undefined, unspecified and implementation-defined behavior](http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) – 5gon12eder Feb 14 '15 at 13:12
  • That's the biggest problem with undefined behavior - sometimes, things "just work". That is why you need memory profilers (check out valgrind). – Sergey Kalinichenko Feb 14 '15 at 13:14
  • The explanation is that you have unwarranted expectations. Guessing is not a good way to program. – Kerrek SB Feb 14 '15 at 13:17

1 Answers1

0

Yes, what is happening is that your program is "walking off" the end of an array, and is printing out garbage. "Garbage" in this context can be anything in the computer (memory, etc.). It does not have protections against this like Java or Python does.

Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35