windowswinapiantivirus

VirtualAllocEx Not Allocating Memory to Desired Address


I am using the VirtualAllocEx function from the windows.h header. I'm trying to allocate (reserve and commit) memory at a specified virtual address within some arbitrary process, take Microsoft Paint, for instance.

For some reason, my desktop computer does not allocate memory to the defined address. The code I'm running is as follows:

#include <stdio.h>
#include <windows.h>
#include <stdint.h>

int main(void) {

    typedef intptr_t pid_t;

    pid_t process_PID = 6492; // arbitrary PID for mspaint.exe on my computer
    char *desired_address = (char *) 0x3117d00000; // free usable mem, 2048KB in size.

    size_t alloc_size = 250000;


    HANDLE hProcess = OpenProcess(  PROCESS_ALL_ACCESS,
                                    FALSE, process_PID  );

    LPVOID pAddress = VirtualAllocEx (  hProcess, desired_address, alloc_size,
                                        (MEM_RESERVE | MEM_COMMIT),
                                        PAGE_EXECUTE_READWRITE  );

    printf("Allocating memory at 0x%p\n", pAddress);

    CloseHandle(hProcess);

    return 0;

}

The address I've passed to VirtualAllocEx is free and usable--I've confirmed this using Process Hacker 2. Yet, the function ends up allocating memory at an address that is not even in the virtual memory space of Microsoft Paint, as shown here:

C:\Users\mdelr\programming\c_programming>virtual_alloc
Allocating memory at 0x17D00000

As you can see, 0x17D00000 is not the address defined in the program, which is 0x3117d00000.

Is there some anti-virus software kicking in and allocating to some safe memory space? I was trying to inject some shellcode into the program to display a messagebox when I ran into this error.

Note: My laptop runs the same OS as my desktop, Windows 11; still, this runs perfectly on my laptop.


Solution

  • I was running a 32-bit version of GCC while compiling. Upon compilation, the 64-bit pointer I defined was being partially cut to accommodate the 32-bit nature of the compiler.

    After upgrading to a 64-bit GCC version using the UCRT64 environment provided by MSYS2 (command below), the issue was resolved.

    pacman -S mingw-w64-ucrt-x86_64-gcc