Reputation: 2210
I was browsing around for stuff to do and I got the idea to allocate memory at specific addresses in windows.
So I read a few questions here on stackoverflow, but none actually presenting a working example, so I had to come up with my own because I really wanted to try:
#include <Windows.h>
#include <iostream>
struct Variable {
int var;
};
#define ACCESS() ((Variable*)0x50000000)
int main()
{
DWORD ptr;
VirtualAlloc((void*)0x50000000,sizeof(Variable),MEM_COMMIT | MEM_RESERVE | MEM_PHYSICAL,PAGE_READWRITE);
VirtualProtect((void*)0x50000000,sizeof(Variable),PAGE_READWRITE,&ptr);
ACCESS()->var = 5;
while(!GetAsyncKeyState('Q')){}
}
But this alway causes an access voilation..
What is the correct way to allocate data at a specific address? Because, this way somehow won't work.. yet confusing at the same time with "Why not?".
Edit:
Second code after first answers not working too:
#include <Windows.h>
#include <iostream>
struct Variable {
int var;
};
#define ACCESS() ((Variable*)0x50000000)
int main()
{
std::cout << VirtualAlloc((void*)0x50000000,sizeof(Variable),MEM_COMMIT,PAGE_READWRITE) << std::endl;
std::cout << GetLastError() << std::endl;
ACCESS()->var = 6;
std::cout << ACCESS() << std::endl;
while(!GetAsyncKeyState('Q')){}
}
the return value is 0, which indicates failure and the GetLastError() equals 487,
and 487 according to this page means:
ERROR_INVALID_ADDRESS; Attempt to access invalid address.
So, all I read over the internet and stack overflow is fake? You >Cannot< allocate data at a specified address? And if this is true, why do we need this function anyway?
Next edit:
Seems it's totally possible, working code:
#include <Windows.h>
#include <iostream>
struct Variable {
int var;
};
#define ACCESS() ((Variable*)0x50000000)
int main()
{
std::cout << VirtualAlloc((void*)0x50000000,sizeof(Variable),MEM_COMMIT | MEM_RESERVE,PAGE_READWRITE) << std::endl;
std::cout << GetLastError() << std::endl;
std::cout << ACCESS() << std::endl;
ACCESS()->var = 6;
std::cout << ACCESS()->var << std::endl;
while(!GetAsyncKeyState('Q')){}
}
Upvotes: 2
Views: 4705
Reputation: 32635
The call to VirtualAlloc
is failing. You would have figured that out if you checked its return value.
The reason it's failing comes directly from the documentation: MEM_PHYSICAL
must be used with MEM_RESERVE
and no other values. You likely don't want MEM_PHYSICAL
anyway, it has to do with AWE. Removing the flag will make the allocation succeed.
The call to VirtualProtect
is unnecessary.
The following should work:
#include <windows.h>
int main()
{
VirtualAlloc((void*)0x50000000,0x1000,MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);
*((int*)0x50000000) = 5;
}
Upvotes: 5