简体   繁体   中英

ReadProcessMemory reads Memory backwards?

When using ReadProcessMemory to read memory of an executable file, the first two bytes that I get are reversed. The code is:

SIZE_T dataRead;
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER) malloc(1);
ReadProcessMemory(process, (LPVOID)addr, dosHeader, 2, &dataRead);
printf("%x\n", dosHeader->e_magic);

The above outputs 5A4D instead of 4D5A. Why would that be? Could it endianess?

Thanks in advance.

Yes, this is due to endianness. The first byte in the file is 0x4d , the second byte is 0x5a . When you print these using %x , they are interpreted as being a little endian number, so the bytes are swapped when they are printed. Consider, as a self-contained example, the following program:

#include <cassert>
#include <cstdio>

int main()
{
    assert(sizeof(unsigned) == 4);

    char bytes[4] = { 0x12, 0x34, 0x56, 0x78 };
    std::printf("%x\n", *reinterpret_cast<unsigned const*>(bytes));
}

On a system with a little-endian byte ordering, the output will be 78563412 . (This example program ignores potential alignment issues; since you are using Visual C++, there will be no problems.)

Note also that you are overrunning your one byte allocation (you malloc(1) but read two bytes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM