tags:

views:

120

answers:

2

I am using GetModuleHandle in my function. That function gets called every time I do an operation. I want to know if that function gets called again and again, will the GetModuleHandle cause any handle leaking (stack overflow or memory leaks or anything else). I actually know when it is getting called and when the break point is hit. But I am not able to figure out if GetModuleHandle is causing any handle leaks. Can anyone help me answer that. Thanks, and below is the function that gets called repeatedly on an operation.

void Myfunc(int iCtrlID) { HINSTANCE hinst = GetModuleHandle("r.dll");

s.LoadString(hinst, iCtrlID); // more code here // }

+1  A: 

You can call GetModuleHandle() all you want. My recollection is that, if you inspect the value, generally it is the same handle returned each time in your process (it may be different in a different process). This doesn't cause any memory leakage.

You can call FreeLibrary() on the handle to unload the dll if you're concerned about that memory, but in practice this is often tricky and most processes will just wait for the process to exit to unload dynamically loaded modules.

Okay, I just tested it with the following code:

  HANDLE h1 = GetModuleHandle(L"user32.dll");
  HANDLE h2 = GetModuleHandle(L"user32.dll");
  HANDLE h3 = GetModuleHandle(L"user32.dll");

Each handle is the same, and it's just the base address of the DLL (you can verify by using the Modules window in Visual Studio).

Typically DLLs don't move around once they are loaded, so you should be able to cache the value returned the first time you call it, so you save the overhead of the extra function call everytime you want to load a string.

jeffamaphone
Thanks, I see the same address for the handles everytime.
rajat
+2  A: 

From the documentation:

The GetModuleHandle function returns a handle to a mapped module without incrementing its reference count. Therefore, use care when passing the handle to the FreeLibrary function, because doing so can cause a DLL module to be unmapped prematurely.

Read: you crash if you try to free the handle. Don't cleanup and you're fine.

Alexander Gessler
I read that definition in the msdn library regarding the reference cont and the free library function. I am not passing those handles to the FreeLibrary function. I just want to be sure if my code is not causing any leaks.
rajat
Judging from your code sample: no, you're not leaking anything.
Alexander Gessler
Thanks Alexander.
rajat