stone liew
stone liew

Reputation: 19

“Attempted to read or write protected memory. This is often an indication that other memory is corrupt.” In C# program

my code

//Marshal.Copy(bytes, 0, P2request, Marshal.SizeOf(request));
 Marshal.StructureToPtr(request, P2request,true);
 

this C# code is for communicate with hardware with C++ dll,so i should use Marshal.StructureToPtr to transfer structure to pointer ,but when i do so, it will trig a error (“Attempted to read or write protected memory. This is often an indication that other memory is corrupt.”).

Althrough the error is solved ,i cannot realize why? hope anybody can help!

Once I add Marshal.Copy() to clear the buffers ,the mistake will disappear. this means only when i clear the buffer, Marshal can write it?

// it works
 Marshal.Copy(bytes, 0, P2request, Marshal.SizeOf(request));
 Marshal.StructureToPtr(request, P2request,true);
 

And when i set third parameter to false (which is Marshal.StructureToPtr(request, P2request,false);),the problem will be solved too.

//it works
//Marshal.Copy(bytes, 0, P2request, Marshal.SizeOf(request));
 Marshal.StructureToPtr(request, P2request,false);
 

Upvotes: 0

Views: 287

Answers (1)

shingo
shingo

Reputation: 27307

The explanation of the 3rd parameter of StructureToPtr:

true to call the DestroyStructure(IntPtr, Type) method on the ptr parameter before this method copies the data. The block must contain valid data.

The remark of the method AllocHGlobal:

Also, the allocated memory is not zero-filled.

Therefore, when you call the method StructureToPtr, there is a chance to free an invalid address, which can trigger the exception.

Upvotes: 5

Related Questions