3

In Unity, I had a bitstream system which required constant pinning of arrays to work with. I'm optimising this out by allocating a block of unmanaged memory and maintaining pointers to it while the system is alive. A note in case this is suggested; this doesn't have to be unmanaged memory, there is no interop, but I want to avoid the additional overhead on the GC of using the alternative of a GCHandle pinned block.

Anyhow, I allocate with a wrapper; AllocRaw::Alloc:

public static void* Alloc(int size) => Marshal.AllocHGlobal(size).ToPointer();

I cache the result of this to later call Marshal.FreeHGlobal, and cast it to a byte* which is used by the system.

As soon as I write to any of these pointers, Unity segfaults, claiming an access violation at address 0. If I step through it manually with a debugger, however, everything completes fine. As soon as control is returned to Unity, it crashes.

I've had issues with Unity running over unmanaged memory before (where it owns the memory but shouldn't write to it), albeit in a different project and without any manual allocation. Is it possible that Unity is somehow referencing the memory which I allocate, and writing to it is causing a memory stomp?

Apologies for the broadness of this question, but I'm at a loss as far as debugging this goes at this point. I'm looking for any suggestions around the possibility of a memory stomp occurring, and steps I might take (from managed code, with no data breakpoints available) to debug this.

EDIT: I should also add that this a test case of only a few hundred kb, and allocation and freeing without writing causes no issues.

Daedalus
  • 86
  • 10

0 Answers0