If I have a function foo() and I want to use VirtualProtectEx() to change the property
of a variable which is in the function foo().
Like this
VirtualProtectEx( GetCurrentProcess(), p, sizeof(DWORD), PAGE_READONLY, &old);
When I set “PAGE_READONLY” and compile it, the massage will show access violation.
If I set “PAGE_READWRITE”, it will execute successfully.
What’s the problem?
The problem with your code is that
pis stored in the stack. By callingVirtualProtectEx, it will affect the whole page, not justp(Each memory page is smallest entity that cannot be fragmented any further). Therefore, if you try to change the permission for justp, it will change the permission of the entire page(entire stack in your case). And if you make the stack read-only, it would not be possible to execute your program anymore and will cause you to have memory access violation exception. So, in order to solve this problem consider allocatingpin heap and freeing them when you are done with it.