Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak - release and delete

IFSUPCUTILSize* size = NULL;
CoCreateInstance(CLSID_UTILSize, NULL, CLSCTX_INPROC_SERVER, IID_IFSUPCUTILSize,    reinterpret_cast<void**>(&size));
            
if (size != NULL){
size->Release();
size = NULL;
}
delete size;

Do I need "delete size" in the code above? If I include "delete size", will I have a memory leak because I did not use New? Or is there a New inside the call to CoCreateInstance. I built this with VC++ 6.

like image 997
dysonfree Avatar asked Aug 25 '11 19:08

dysonfree


People also ask

What is memory leak and out of memory?

A memory leak in Java is when objects you aren't using cannot be garbage collected because you still have a reference to them somewhere. An OutOfMemoryError is thrown when there is no memory left to allocate new objects.

Does memory leak go away?

Memory leaks don't result in physical or permanent damage. Since it's a software issue, it will slow down the applications or even your whole system. However, a program taking up a lot of RAM space doesn't always mean its memory is leaking somewhere. The program you're using may really need that much space.

What causes memory leak C++?

Memory leakage occurs in C++ when programmers allocates memory by using new keyword and forgets to deallocate the memory by using delete() function or delete[] operator. One of the most memory leakage occurs in C++ by using wrong delete operator.


1 Answers

COM interfaces are reference counted. CoCreateInstance() returns an interface pointer to a COM object whose reference count has already been incremented. Calling Release() decrements the reference count. When the reference count falls to zero, the COM object frees itself automatically. DO NOT call delete on a COM interface pointer! Always use Release() only.

like image 189
Remy Lebeau Avatar answered Sep 27 '22 21:09

Remy Lebeau