Native c++ (mingw) plugin works in editor but not in build

I have a minimal c++ script that’s called from a minimal c# script. The dll is compiled on Windows 10 using mingw g++ and it works fine in the editor. Build an run however leads to the following error message:

Plugins: Failed to load ‘C:/(…)/dll-example_Data/Plugins/libTest.dll’ with error 'A dynamic link library (DLL) initialization routine failed.

Here’s the .cs file:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;

public class TestScript : MonoBehaviour
    [DllImport("libTest", CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
    public static extern int TestFunction();

    void Start()
        Debug.LogFormat("libTest says: {0}", TestFunction());

And the .cpp:

extern "C" {
int __stdcall __declspec(dllexport) TestFunction() {
        int* test = new int[1]; // removing this line will make everything work when building
        return 4;

Here’s how I build it:

g++ -O2 -g -Wall -c -fmessage-length=0 Test.cpp
g++ -shared -o libTest.dll Test.o

So If I delete the marked line (int* test = …), recompile and replace the .dll everything works fine using the build .exe and the editor.

Any suggestions would be appreciated!

I’ve tried finding a difference between the dlls using ldd, objdump and dumpbin.exe but couldn’t find anything obvious, however I’m not quite an expert with these tools.

Using the Microsoft Debug Diagnostic Tool I found out that I get following exception:

In dll-example__PID__(…)C0000005.dmp the assembly instruction at libTest!TestFunction+ee80 in C:(…)\dll-example_Data\Plugins\libTest.dll has caused an access violation exception (0xC0000005) when trying to read from memory location 0x92fff800 on thread 0

That made me think the error could be due to something -fPIC related but adding this flag to the compiler didn’t help either.