trying to read directly from memory (C#)

1

I tried to read a byte value directly from the memory with C#. I tried it with Marshal.Copy Marshal.ReadByte and many different addresses in all ranges.

Always I get the exception:

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

What can I do to access the protected memory?

I using some memory viewing tools and these tools can access the whole memory without problems.

Example:

IntPtr bufPtr = new IntPtr(0x00000772);
byte data = Marshal.ReadByte(bufPtr);

The address is not within a known process so I can not use ReadProcessMemory() or something similar.

c#
memory
asked on Stack Overflow Jan 1, 2013 by Schmidko • edited Jan 1, 2013 by marc_s

1 Answer

5
  IntPtr bufPtr = new IntPtr(0x00000772);

That will never work, the bottom 64KB of the virtual memory address space is reserved and can never be referenced. This is a counter-measure against null pointer bugs, using one by accident ensures that an AccessViolationException is thrown, usually terminating the program.

You cannot pick arbitrary addresses, the number you pick must be the address of an area of virtual memory that's mapped. Finding valid addresses requires at least a pinvoke call to VirtualQuery(). The usefulness is still quite limited, out of the millions of possible valid addresses, you'll have no idea what you are actually reading. Add in the garbage collector that randomly moves stuff around when it compacts the heap and your odds of finding anything useful are slim to none.

You can get some insight in how the virtual memory address space of a process is used from the SysInternals' VMMap utility. An introductory book about operating system design and a book like Windows Internals are required to make sense of it all.

answered on Stack Overflow Jan 1, 2013 by Hans Passant

User contributions licensed under CC BY-SA 3.0