This question already has an answer here:
I declared an integer array on heap like this
int* a = new int;
and then I initialized it like this
for(int i=0; i<100; i++)
a[i] = i;
which worked perfectly but then I tried this
for(int i=0; i<1000; i++)
a[i] = i;
which also worked perfectly.Since I am a newbie to c++ can anyone explain what's the problem in this above declaration because I think the declaration of integer array is not proper or might be anything else?
Best How To :
When you write past the end of an array you get undefined behaviour. The important word is undefined. It may depend on the compiler, the environment, the compiler flags, ...
In you example it worked because you wrote on a memory that is accessible, but you could (non limitative list) :
- try to access unavailable memory and get a segmentation violation
- try to write read only memory
- ovewrite other variable belonging to your own code
- erase your own stack
But as it is undefined behaviour nothing guarantees that this happens. You only know you must never do that.
With recent (decent OS) you cannot crash the system, but only your own application except if you run with admin or root privileges, in what case anything can happen. But with older systems like MS/DOS (or some embedded system) there are no inter application protection and system crash are likely to happen with such program.