-1

I have written a small method that is supposed to allow me to easily overwrite the value of a static constant variable.

Here is the variable I want to change:

static const unsigned int myInt;

Here is the method that I am trying to use:

template<typename T>
void MyClass::SetConstantVariableValue(void* destination, T& value)
{
    memcpy(destination, (const void*)&value, sizeof(value));
}

And here is the statement used to call the method:

int a = 5;
this->SetConstantVariableValue((void*)&myInt, a);

My problem is that it works perfectly if myInt is only static and not constant. As soon as I define it as constant, memcpy crashes from an access violation.

Unhandled exception at 0x596EEB90 (msvcr110d.dll)
0xC0000005: Access violation writing location 0x00AC16B8.

It is my understanding that memcpy ignores the fact that a variable might be constant since it is performed at runtime and has no idea what the datatype is for either the destination or the source. If that is correct, then the combination of being static and const is what is causing the crash. I have not been able to find anything explaining as to why this might cause memcpy to crash. Anyone know what I am doing wrong?

CgRobot
  • 3
  • 3
  • 1
    Why would you want to change the value of a const variable ? Generally speaking, it doesn't make sense. – zentrunix Aug 26 '13 at 01:39
  • I completely agree. However, the issue usually arises when the value needs to be changed once; after it has already been initialized. – CgRobot Aug 26 '13 at 01:45

1 Answers1

1

Any attempt to modify a variable declared const is undefined behavior. In this case, the compiler has chosen to store the const variable in read-only memory.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
  • Is there any way to prevent the compiler from storing it in read-only memory? – CgRobot Aug 26 '13 at 01:35
  • 1
    @CgRobot: Why make it const if you want to modify it? – Vaughn Cato Aug 26 '13 at 01:37
  • I want other classes to be able to access this variable statically, in a read-only manner. However, I needed to set its value once, after it had been initialized. I realize that I could just make an accessor for it, but I had never tried doing it this way before. – CgRobot Aug 26 '13 at 01:43
  • @CgRobot: An alternative is to have a const reference to a non-const object. – Vaughn Cato Aug 26 '13 at 01:46
  • That sounds like a more proper way of accomplishing what I want. I am still curious though for future reference as to how my current method might be modified to work. If there is any way at all of course. Thanks for the help! – CgRobot Aug 26 '13 at 01:53