2

I have created my own DLL and am calling methods using LoadLibrary/GetProcAddress. The application crashes whenever "new" is used.

Below is the complete code.

test_app.cpp

#include <windows.h>

int main()
{
    typedef int (*Test)();
    HINSTANCE hGetProcTest = LoadLibraryA("DLLFunctions.dll");
    Test test_method = (Test)GetProcAddress(hGetProcTest, "Test");
        
    test_method();

    return 0;
}

dll_entry_point.cpp

#include <windows.h>

int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
{
  return 1;
}

int WINAPI WinMain(      
    HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpCmdLine,
    int nCmdShow)
{  
  return 0;
}

dll_functions.h

#ifndef UnitFunctionsH
#define UnitFunctionsH

#ifdef __cplusplus
extern "C"
{
#endif

__declspec (dllexport) int Test();

#ifdef __cplusplus
}
#endif

#endif

dll_functions.cpp

#include "dll_functions.h"
#include <array>

int Test()
{
    // Crash Happens Here
    std::array<int, 5> *arr = new std::array<int, 5>;
    return 1;
}

Running test_app.exe results in the following error after creating the array:

Thread 1 received signal SIGSEGV, Segmentation fault. 0x00000000000094d8 in ?? ()

Allocating memory within the application, not in the DLL, works perfectly fine.

From debugging in vscode I can see that it always crashes whenever I do "new". If I simply did used std::array<int, 5> arr; instead, then it doesn't crash.

I am doing the following to create the DLL (I have tried without the -g as well):

g++ -g -c dll_entry_point.cpp && g++ -g dll_functions.cpp dll_entry_point.o -o DLLFunctions.dll && g++ -g test_app.cpp -o test_app

  • 2
    Sounds like the DLL's RTL (which includes the memory manager used by `new`) wasn't initialized properly when the DLL was loaded into memory, as you are not linking in any compiler-provided RTL object files that would contain startup code to initialize the RTL. Also, why does your DLL have both a `DllEntryPoint()` and a `WinMain()`? Also, you are missing error handling to make sure `LoadLibraryA()` and `GetProcAddress()` are successful before you call `test_method()` – Remy Lebeau Sep 14 '22 at 21:30

1 Answers1

0

Fixed by adding -mdll to the dll creation command.

Fixed command: g++ -g dll_functions.cpp dll_entry_point.o -o DLLFunctions.dll -mdll