The code:
int *ptr = new int[10];
int *q = ptr;
delete q;
works fine without any issues (no run-time error).
However, the following code:
int *ptr = new int[10];
int *q = ptr;
q++;
delete q;
results in run-time error.
I am using Microsoft Visual Studio-8 and Win-7 as platform.
I am not able to figure out why there is a run-time error in the second case?
Your code is causing an Undefined Behavior. An Undefined Behavior means anything can happen, the behavior cannot be defined. The program works just by pure luck its behavior cannot be explained.
Basically,
If you are allocating dynamic memory with
newyou MUST usedeleteto deallocate it.If you are allocating dynamic memory with
new[]you MUST usedelete[]to deallocate it.It is undefined behavior to pass any address to
deletewhich was not returned bynew.Here is the quote from the Standard.
As per C++03 Standard § 3.7.4.2-3:
In C++ it is better to use RAII(SBRM) by using Smart pointers instead of raw pointers, which automatically take care of the memory deallocations.