I am trying to create a game trainer for a game. I have found the needed memory addresses and now I want to write my values into that address.
For example: address of ammo is: 0x0E9AFD07
The WriteProcessMemory()
function in the Windows API can do this.
My source:
int main(){
DWORD pid;
int address = 0x0E9AFD07;
const int data = 20;
HWND hwnd = FindWindow(0 , "Max Payne v1.05");
GetWindowThreadProcessId(hwnd , &pid);
HANDLE hndl = OpenProcess(PROCESS_ALL_ACCESS , false ,pid);
WriteProcessMemory(hndl , &address , &data , 4 , NULL);
return 0;
}
But this code does not work!
If I should use WriteProcessMemory
like below:
WriteProcessMemory(hndl , (void*)0x0E9AFD07 , &data , 4 , NULL);
then the second parameter of the function is LPVOID
type and I read that LPVOID
is a pointer to anything.
So, why I can't pass a pointer to int
(address variable) for the second parameter?
And why should I use (void*)
?
Note that your two code snippets are not equivalent; rather, they are asking the WriteProcessMemory
function to write data to different locations.
In the second snippet, you pass 0x0E9AFD07
(as a void*
), which tells the function to write the data to memory starting at the given address (the hex value passed).
However, in the first snippet, you are passing the address of the int
variable (which just happens to contain the value 0x0E9AFD07
); this will instruct the function to write data to the location of that variable - thus, overwriting the 0x0E9AFD07
value that is there (or failing in the attempt to do so).
If you want to pass an address stored in a local variable, then you need to cast the value of that variable to a void*
pointer, like this:
int main(){
DWORD pid;
int address = 0x0E9AFD07;
const int data = 20;
HWND hwnd = FindWindow(0 , "Max Payne v1.05");
GetWindowThreadProcessId(hwnd , &pid);
HANDLE hndl = OpenProcess(PROCESS_ALL_ACCESS , false ,pid);
// The "int" variable's VALUE is the target address, so cast/pass that...
WriteProcessMemory(hndl , (void*)address , &data , 4 , NULL);
return 0;
}