P/Invoke and memory related intermittent crash

147 Views Asked by At

I've implemented this APIs some time ago and everything was working quite well until some weeks ago when I noticed it, The intermittent crash, the famous Marshaling related in .NET "Attempted to read or write protected memory. This is often an indication that other memory is corrupt". I noticed that there was also a certain pattern related to the number of opened applications that I have, so I assume its something related to the memory. But checking the available memory, it still pointing to a healthy state when it's crashing. Please see bellow the functions:

C++  
__declspec(dllexport) char* xReadData(char *p_buffer, int offset, int size)
{
    // do nothing
    return p_buffer; 
}

C#
[DllImport(PathToDll, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr xReadData([Out] IntPtr buffer, int offset, int size);

// SIZE = amount of bytes to read (2^13)
IntPtr pnt = Marshal.AllocHGlobal(SIZE);
...
try
{                                
    xReadData(pnt, 0, SIZE); >> crashing on [Managed to Native Transition]  

}
catch
{
}
...
Marshal.FreeHGlobal(pnt);

According to my analysis it crashes in between the completion of the native function and the returning to the managed code again.

Thanks in advance.

1

There are 1 best solutions below

5
On
if ((offset>-1) && (offset + size<= MAX_BYTES))
{
    memcpy(p_buffer, &(input_list[offset]), size);
}

That condition will definitely throw exception when offset is equal to MAX_BYTES and size is equal to zero.

input_list[MAX_BYTES] is out of bounds.

Also, I hope you deallocate the buffer :-')