Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. question about memory allocation in win32 dll

question about memory allocation in win32 dll

Scheduled Pinned Locked Moved C / C++ / MFC
c++helpperformancetutorialquestion
6 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    Jim Howard
    wrote on last edited by
    #1

    Howdy folks, Please help me understand the concept of memory allocation in win32 dll's written in c++. I have found that when I use 'new' and 'delete' I often get access violations. I've done some reading, but am still confused. Blaszczak is silent on this issue. Brain ("Win32 System Services") says to use 'GlobalAlloc' in dlls, but doesn't really say why. Here is an example that confuses me: //Junkdll.cpp #include #define _COMPILING_DCC237C0_6FEE_11d5_A91C_0050DAC6D85C_ #include "JunkDll.h" HGLOBAL secret; //char* secret BOOL WINAPI main(HINSTANCE dllhandle, DWORD reason, LPVOID situation) {  switch(reason)   {   case DLL_PROCESS_ATTACH :    OutputDebugString("DLL_PROCESS_ATTACH\n");    secret = GlobalAlloc(GPTR,100*sizeof(char));    //new char[100] causes access violation;    strcpy((char*)secret,"The meaning of life is 42.\n");     break;   case DLL_PROCESS_DETACH:    OutputDebugString("DLL_PROCESS_DETACH\n");  //delete(secret)doesn't work    if(secret)      GlobalFree(secret);    break;   }  return TRUE; } char* getMeaningOfLife(char* buffer) {  if(buffer != 0)  strcpy(buffer,(char*)secret);  return buffer; } `In the above example, if I define 'secret' as char* secret, and then use new and delete to allocate a buffer for it I get an acess violation. When I use GlobalAlloc as shown, it works. The help files say to use the heap function instead of GlobalAlloc, but I've never used them. I'm clearly missing the big picture on memory allocation for dlls. Brain talks about four different dll memory models, but I'm not grocking the concept. thanks Jim :confused:`

    T 1 Reply Last reply
    0
    • J Jim Howard

      Howdy folks, Please help me understand the concept of memory allocation in win32 dll's written in c++. I have found that when I use 'new' and 'delete' I often get access violations. I've done some reading, but am still confused. Blaszczak is silent on this issue. Brain ("Win32 System Services") says to use 'GlobalAlloc' in dlls, but doesn't really say why. Here is an example that confuses me: //Junkdll.cpp #include #define _COMPILING_DCC237C0_6FEE_11d5_A91C_0050DAC6D85C_ #include "JunkDll.h" HGLOBAL secret; //char* secret BOOL WINAPI main(HINSTANCE dllhandle, DWORD reason, LPVOID situation) {  switch(reason)   {   case DLL_PROCESS_ATTACH :    OutputDebugString("DLL_PROCESS_ATTACH\n");    secret = GlobalAlloc(GPTR,100*sizeof(char));    //new char[100] causes access violation;    strcpy((char*)secret,"The meaning of life is 42.\n");     break;   case DLL_PROCESS_DETACH:    OutputDebugString("DLL_PROCESS_DETACH\n");  //delete(secret)doesn't work    if(secret)      GlobalFree(secret);    break;   }  return TRUE; } char* getMeaningOfLife(char* buffer) {  if(buffer != 0)  strcpy(buffer,(char*)secret);  return buffer; } `In the above example, if I define 'secret' as char* secret, and then use new and delete to allocate a buffer for it I get an acess violation. When I use GlobalAlloc as shown, it works. The help files say to use the heap function instead of GlobalAlloc, but I've never used them. I'm clearly missing the big picture on memory allocation for dlls. Brain talks about four different dll memory models, but I'm not grocking the concept. thanks Jim :confused:`

      T Offline
      T Offline
      Tomasz Sowinski
      wrote on last edited by
      #2

      It should be possible to call new in DllMain called with DLL_PROCESS_ATTACH parameter. Each MFC extension DLL has a call to new in its initialization code:

      if (dwReason == DLL_PROCESS_ATTACH)
      {
      TRACE0("CORE.DLL Initializing!\n");

      	if (!AfxInitExtensionModule(CoreDLL, hInstance))
      		return 0;
      
      	**new CDynLinkLibrary(CoreDLL);**
      }
      

      Is DllMain the 'raw' entrypoint to your DLL, or is it called from _DllMainCRTStartup? Put the breakpoint in the DllMain and check the stack. Tomasz Sowinski -- http://www.shooltz.com

      J 1 Reply Last reply
      0
      • T Tomasz Sowinski

        It should be possible to call new in DllMain called with DLL_PROCESS_ATTACH parameter. Each MFC extension DLL has a call to new in its initialization code:

        if (dwReason == DLL_PROCESS_ATTACH)
        {
        TRACE0("CORE.DLL Initializing!\n");

        	if (!AfxInitExtensionModule(CoreDLL, hInstance))
        		return 0;
        
        	**new CDynLinkLibrary(CoreDLL);**
        }
        

        Is DllMain the 'raw' entrypoint to your DLL, or is it called from _DllMainCRTStartup? Put the breakpoint in the DllMain and check the stack. Tomasz Sowinski -- http://www.shooltz.com

        J Offline
        J Offline
        Jim Howard
        wrote on last edited by
        #3

        Thanks Thomas. The example that I gave is a pure 'C' dll, not using MFC or C++ classes. I call the function from an exe program by either late binding (loadlibrary) or early binding (linking in the lib file). In both cases 'secret = new char[100]' throws an access violation. I'm sure that 'new' works in dll's under some circumstances. Looking through the MFC source, they are doing all kinds of fancy stuff in AfxInitExtensionModule with both memory and threading. Something the MFC programmer did lets new work, but I don't percieve how they did it. I'm just trying to understand why my new's don't work in this simple case. If I can understand that, then perhaps I can understand what MFC is doing in that deceptively simple call to AfxInitExtensionModule. Jim:confused:

        T 1 Reply Last reply
        0
        • J Jim Howard

          Thanks Thomas. The example that I gave is a pure 'C' dll, not using MFC or C++ classes. I call the function from an exe program by either late binding (loadlibrary) or early binding (linking in the lib file). In both cases 'secret = new char[100]' throws an access violation. I'm sure that 'new' works in dll's under some circumstances. Looking through the MFC source, they are doing all kinds of fancy stuff in AfxInitExtensionModule with both memory and threading. Something the MFC programmer did lets new work, but I don't percieve how they did it. I'm just trying to understand why my new's don't work in this simple case. If I can understand that, then perhaps I can understand what MFC is doing in that deceptively simple call to AfxInitExtensionModule. Jim:confused:

          T Offline
          T Offline
          Tomasz Sowinski
          wrote on last edited by
          #4

          AfxInitExtensionModule has nothing to do with the problem. I can call new without any errors before AfxInitExtensionModule. Anyway, I think your DllMain is called directly by Windows (usually the raw entrypoint is _DllMainCRTStartup), C/C++ runtime is not initialized yet and new/malloc fail. Check the KB article Q94248 for more info. BTW, if your DLL is pure 'C', how could you compile 'new char[100]'? Tomasz Sowinski -- http://www.shooltz.com

          J 1 Reply Last reply
          0
          • T Tomasz Sowinski

            AfxInitExtensionModule has nothing to do with the problem. I can call new without any errors before AfxInitExtensionModule. Anyway, I think your DllMain is called directly by Windows (usually the raw entrypoint is _DllMainCRTStartup), C/C++ runtime is not initialized yet and new/malloc fail. Check the KB article Q94248 for more info. BTW, if your DLL is pure 'C', how could you compile 'new char[100]'? Tomasz Sowinski -- http://www.shooltz.com

            J Offline
            J Offline
            Jim Howard
            wrote on last edited by
            #5

            Thank Tomasz, that clears it up. My problem was indeed that the C runtime was not being intialized because I inadvertantly had "main" instead of DllMain as my entry point. The KB article was very helpful, and my example now works with new and delete. I think I understand that the price of using new and delete is that I have to load the C runtime. If for some reason I didn't want the C runtime, then I take it that I could use GlobalAlloc instead of new and delete. Sorry the ambiguity about pure 'C'. My interface is straight 'C', but my implementation uses C++ features. thanks Jim :)

            J 1 Reply Last reply
            0
            • J Jim Howard

              Thank Tomasz, that clears it up. My problem was indeed that the C runtime was not being intialized because I inadvertantly had "main" instead of DllMain as my entry point. The KB article was very helpful, and my example now works with new and delete. I think I understand that the price of using new and delete is that I have to load the C runtime. If for some reason I didn't want the C runtime, then I take it that I could use GlobalAlloc instead of new and delete. Sorry the ambiguity about pure 'C'. My interface is straight 'C', but my implementation uses C++ features. thanks Jim :)

              J Offline
              J Offline
              Jim Howard
              wrote on last edited by
              #6

              When I initialize the C runtime the release version of my example program is 44K. When I don't use the C runtime and use GlobalAlloc/GlobalFree instead, my program is only 20K. For routine desktop apps that 24K delta is nothing, for space critical programs it could make a difference. Jim

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups