Can this code cause managed heap corruption?

I'm trying to debug a crash that happens in our application during garbage collection, and looking at the code, I found two related code snippets that, if not the cause of the problem, are at least suspicious to me:

[StructLayout(LayoutKind.Sequential, Size = 96, CharSet = CharSet.Ansi, Pack=1)]
public class MilbusData
{
  public System.Int64 TimeStamp;
  public System.Int16 Lane;
  public System.Int16 TerminalAddress;
  public System.Int16 TerminalSubAddress;
  public System.Int16 Direction;   
  public System.Int64 ErrorCounter;   
  public System.Int64 MessageCounter;   
  public System.Int16 RTErrorState;     
  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
  public System.UInt16[] Data;
}

Please note that, in my opinion, the structure actually has a size of at least 98 bytes, but is declared as 96 bytes in length (the code compiles).

The second suspicious part of the code is related to the above structure:

MilbusData^ ret = nullptr;
if (m_Stream->Read(m_RawData, 0, sizeof(TMilbusData)) == sizeof(TMilbusData))
{
  GCHandle pinnedRawData = GCHandle::Alloc(m_RawData, GCHandleType::Pinned);

  ret = (MilbusData^)Marshal::PtrToStructure(pinnedRawData.AddrOfPinnedObject(), 
                                             MilbusData::typeid);

   pinnedRawData.Free();
}

where m_RawData is a simple unsigned array, and TMilbusData is C ++ (native) code, similar to the structure above, defined as

typedef struct
{
  __int64 TimeStamp;
  short Lane;
  short TerminalAddress;
  short TerminalSubAddress;
  short Direction;
  __int64 ErrorCounter;
  __int64 MessageCounter;
  short RTErrorState;
  unsigned char Data[64];
} TMilbusData;

, ( , MilbusData ).

, , , , . , :

  • ?
  • , , ?

. , , , , ( ), . , i) # ii) . ​​ "" ( ), , .

+5
1

, 96 ? , ?

, , 16 , 32 .

, 96 , 96 , .

, 1) 96 . 2) .

, , . , ​​, .

EDIT: , , , , ( ) GC. , i) # ii) . "" ( ), , ..

, , 96 , , , , . , ?

, Data , , .

+3

All Articles