Luchian Grigore
Luchian Grigore

Reputation: 258648

Possible memory leak?

I have the following code:

void customHandleException  (_EXCEPTION_POINTERS* ExceptionInfo)
{
      char* x = (char*)ExceptionInfo->ExceptionRecord->ExceptionInformation[0];
      delete[] x;
}


void foo()
{
   char* x = new char[ 256 ];
   ULONG_PTR* args = new ULONG_PTR[1];
   args[0] = (long)x;
   RaiseException(EXCEPTION_CODE,0,1,args);
}

Leaving all else aside, char* x from customHandleException() will point to the char array allocated in foo(). Will this cause a memory leak or will the delete work?

Upvotes: 0

Views: 137

Answers (1)

Alok Save
Alok Save

Reputation: 206626

You should be using delete[]. Memory allocated with new[] MUST be deallocated with delete[].

Reference:

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.

Upvotes: 6

Related Questions