0

I am trying to make the following contrived example work. In the code below, I declare a const global variable and attempt to modify it by first using VirtualProtect to make the address writable.

#include <cstdio>
#include "windows.h"

int const ConstantZero = 0;

int main() {
    DWORD OldProtect = NULL;
    VirtualProtect((void *)&ConstantZero, sizeof(int), PAGE_READWRITE, &OldProtect);
    const_cast<int&>(ConstantZero) = 1;
    printf("ConstantZero is %d\n", ConstantZero);
}

While this works, the argument to the printf function is passed as an immediate value, rather than a variable. Is there anyway to make the compiler pass the argument as a variable instead? I am using MSVC compiler version 19.26.28806 for x86.

user1720897
  • 1,216
  • 3
  • 12
  • 27
  • 3
    This is undefined behavior. Why don't you make `ConstantZero` non-`const` if you're going to change it? – Stephen Newell Jul 28 '20 at 04:51
  • `volatile int const ConstantZero = 0;` is supposed to prevent such optimizations, see more [here](https://stackoverflow.com/questions/4592762/difference-between-const-const-volatile) (C) and [here](https://stackoverflow.com/questions/33684826/c-why-does-the-const-volatile-type-qualifier-exist) (C++). – dxiv Jul 28 '20 at 04:55
  • @StephenNewell Because I want to use `VirtualProtect` to mark the addess writable. This is just a contrived example. – user1720897 Jul 28 '20 at 04:56

0 Answers0