I recently experienced a memory leak issue. I troubleshooted the issue for quite a long time and subsequently found out that throwing an exception (I use my own exception classes) causes this memory leak. The code of throwing the exception is as following:
HINSTANCE lib = LoadLibrary(path.c_str());
if(!lib)
{
DWORD werror = GetLastError();
ostringstream stream;
stream << werror;
string errstring = "Error " + stream.str();
errstring.append(" - " + libraryName);
throw LibraryLoadException(MOD_ERROR_LIB_LOAD, errstring.c_str());
}
The resulting output looks like:
Detected memory leaks!
Dumping objects ->
{351} normal block at 0x0044D208, 32 bytes long.
Data: <Error 126 - note> 45 72 72 6F 72 20 31 32 36 20 2D 20 6E 6F 74 65
{347} normal block at 0x0043BD98, 8 bytes long.
Data: <4 > > 34 F2 3E 00 00 00 00 00
{344} normal block at 0x0043FDE8, 32 bytes long.
Data: <126 > 31 32 36 CD CD CD CD CD CD CD CD CD CD CD CD CD
{302} normal block at 0x004409D8, 8 bytes long.
Data: <4 > > 34 F3 3E 00 00 00 00 00
{301} normal block at 0x0043FAF0, 8 bytes long.
Data: <P > > 50 F3 3E 00 00 00 00 00
Object dump complete.
As seen in the output of the visual studio leak CrtDbg, there are actual values of the objects used in the if block. All these objects including the exception itself (and all its attributes) are allocated on stack, though, so there cannot be a fault of me forgetting to deallocate something on heap. I empirically tested this and the leak is definitely caused by the objects in the if block (after removing several objects like the string, DWORD and the stream the leaks grow fewer).
Can anyone tell me what am I doing (or what is) wrong over here?
Thank You in advance