Search code examples
c++windowswinapimemoryreadprocessmemory

How to properly use ReadProcessMemory without raising warnings


What is the correct way to use ReadProcessMemory?

I am currently using it like this:

DWORD read_mem(DWORD addr)
{
    DWORD buffer = 0x0;
    if (!ReadProcessMemory(phandle, LPCVOID(addr), &buffer, sizeof(DWORD), nullptr))
    {
        return false;
    }

    return buffer;
}

This causes a warning due to addr being wrongly casted.

warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

Other example code I've seen such as this uses the same approach.

So what is the proper way to use this function without getting a warning?


Solution

  • "cast to pointer from integer of different size" - this means that DWORD and void* are different byte sizes, which can only happen if you are compiling your code for 64-bit, as they are the same byte size in a 32-bit compilation.

    From the MSDN documentation, Windows Data Types:

    DWORD
    A 32-bit unsigned integer. The range is 0 through 4294967295 decimal.

    A DWORD is simply not large enough to hold a 64-bit memory address (the other code you mention will similarly only work correctly in 32-bit).

    Change Addr (and whatever code you are using to determine the value of Addr) to use DWORD_PTR instead:

    DWORD_PTR
    An unsigned long type for pointer precision. Use when casting a pointer to a long type to perform pointer arithmetic. (Also commonly used for general 32-bit parameters that have been extended to 64 bits in 64-bit Windows.)

    Then Addr will be the correct byte size whether you compile for 32-bit or 64-bit.