On Apr 9, 5:50 pm, "Willy Denoyette [MVP]"
<willy.denoye...@telenet.bewrote:
"O.B." <funkj...@bellsouth.netwrote in message
news:11*********************@n59g2000hsh.googlegro ups.com...
I've got this C# .NET 2005 application that has some unmanaged code.
At random times, I get:
An unhandled expection of type 'System.AccessViolationException'
occurred in Unknown Module.
Additional information: Attempted to read or write protected memory.
This is often an indication that other memory is corrupt.
I have enabled "unmanaged code debugging" and when the error occurs,
the breakpoint is at random places within memcpy.asm. The call stack
shows nothing but system dll's (none of my code) ... ntdll.dll,
mscorwks.dll, mscorlib.ni.dll, System.ni.dll, and kernel32.dll.
I also have a try/catch around Main and the exception is not being
thrown within my application.
Are there any applications available to help hunt down this memory
leak?
This is not a memory leak, it's a bug in the way you call the unmanaged code and the way you
pass data across the managed/unmanaged border. Mostly this is due to wrong PInvoke
declarations.
Willy.
I think I have figured out where the problem was occurring. I have a
TCP socket that invokes an asynchronous callback. Where
tempState.Buffer contains the 16 bytes of data read by the socket and
Header is an ExplicitLayout struct:
IntPtr headerPtr = Marshal.UnsafeAddrOfPinnedArrayElement(
tempState.Buffer, 4); // ignore first 4 bytes
Header pduHeader = (Header)Marshal.PtrToStructure(
headerPtr, typeof(Header));
So I changed it to the following:
IntPtr pBuffer = Marshal.AllocHGlobal(12);
Marshal.Copy(tempState.Buffer, 4, pBuffer, 12); // ignore first 4
bytes
Header pduHeader = (Header)Marshal.PtrToStructure(
pBuffer, typeof(Header));
Marshal.FreeHGlobal(pBuffer);
And this works without a glitch. While I'm happy that it works, could
someone please explain to me why it works? And why the problem
occurred randomly and not every time the code was executed? Thanks.