I am trying to learn how to access values from memory. To learn this I made 2 programs in C using Visual Studio Code. One of which just prints it's process id along with assigning then printing the new integer (it then runs in an infinite loop). here is the following output when ran from my cmd.
Process ID: 4209760
Integer Value: 123456 Memory Location: 0061FF14
I then have a second C program that runs in my cmd which attempts to read the above integer's value (aka 123456). Here is what my code looks like.
int main()
{
printf("Test 1 \n");
DWORD access = PROCESS_ALL_ACCESS;
DWORD pid = 4209760;
HANDLE hProcess = OpenProcess(access, FALSE, pid);
printf("Test 2 \n");
if(hProcess == NULL) {
printf("OpenProcess Failed GetLastError: %d \n", GetLastError());
system("pause");
return EXIT_FAILURE;
}
printf("Test 3 \n");
int memoryAddress = 0x0061FF14;
int intRead = 0;
BOOL rpmReturn = ReadProcessMemory(hProcess, (LPCVOID) memoryAddress, &intRead, sizeof(int), NULL);
printf("Test 4 \n");
if (rpmReturn == FALSE) {
printf("ReadProcessMemory failed. GetLastError = %d \n", GetLastError());
system("pause");
return EXIT_FAILURE;
}
printf("INT READ: %i \n", intRead);
return EXIT_SUCCESS;
}
When I run this I get an error right after Test 2 (at hProcess == NULL) which yields error code 87. Looking this error code up here https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499- gives me an invalid parameter error. But when I hover over OpenProcess it says that my parameters should be DWORD, BOOL, and DWORD which is what I provided any ideas what is going on? Furthermore, when I decided to comment out that null check I got another error (Error code 6) in the if statement right after Test 4. This error code just meant that I used an invalid HANDLE which cemented the fact that the problem was originating from a parameter issue with hProcess.
One last thing while looking into this topic I noticed that people used "uintptr_t" as the variable type for memoryAddress which is "an unsigned integer type that is capable of storing a data pointer". However this seems to only be a C++ implantation and my worry is using a normal int will cause issues after I figure out this parameter issue out. I could use unsiged int as the variable type but I am not sure if that is equivalent to uintptr_t in this context.
I also tried to run my programs in administrator mode but that did not change the outcome. Does anyone have any idea what is going on?
Edit: Here is what my first program looks like.
int main() {
int varInt = 123456;
printf("Process ID: %i \n", GetCurrentProcessId);
printf("Integer Value: %i %p \n", varInt, &varInt);
while(true) {
if(getchar()) {
printf("Shutting Down");
return EXIT_SUCCESS;
}
}
printf("Error Shutting Down");
return EXIT_FAILURE;
}