Search code examples
c++windowspointersmemory-corruption

Run-time detection of memory deletion


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?


Solution

  • 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 new you MUST use delete to deallocate it.

    If you are allocating dynamic memory with new[] you MUST use delete[] to deallocate it.

    It is undefined behavior to pass any address to delete which was not returned by new.
    Here is the quote from the Standard.

    As per C++03 Standard § 3.7.4.2-3:

    If a deallocation function terminates by throwing an exception, the behavior is undefined. The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(std::size_t) or operator new(std::size_t, const std::nothrow_-t&) in the standard library, and the value supplied to operator delete[](void*) in the standard library shall be one of the values returned by a previous invocation of either operator new[](std::size_t) or operator new[](std::size_t, const std::nothrow_t&) in the standard library.

    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.