开发者

Does GetModuleHandle function cause any leaks (stack overflow and memory leaks ) in VC++

开发者 https://www.devze.com 2022-12-18 02:14 出处:网络
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 handl

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 // }


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消