Skip to content

gcc – revert compiler’s instructions of making a memory block constant?

Is there a way to somehow remove the constant lock on a memory address during the execution of a program like in compiled languages,

const int value = 100;

is there a way to remove the constant lock from &value address during the execution of the program.

Languages like JavaScript we can also make our variables constant,

const value = 100;

is there a way so that I can remove the constant lock from the memory that was once made constant, JavaScript is a interpreted language so I guess there would be some hacks that can do the similar

Answer

after the termination of the program what exactly happens to that block?

What happens to the virtual memory of your process is decided by the operating system. When the program terminates, the operating system will wipe out any memory that was allocated for your program, regardless of what that memory was being used for. The concept of const has nothing to do with this.

Was the compiler able to remove that const qualifier from that particular block? Can I be able to overwrite that block of memory, if so how can I do that explicitly?

You cannot change how a variable was declared. It stays that way for its entire lifetime. You won’t be able to do this, and even then, it’s undefined behavior to try doing it.

What if I need to overwrite a const block of memory? Is there any way to do that?

If you need to do this, the logic of whatever program you are writing is flawed. You cannot, and should not do this. It is undefined behavior, and in the best scenario will kill your program with a segmentation fault.


Ok, if you really want to kill your program with a segmentation fault caused by writing to a const variable, assuming that your compiler puts global const variables in a read only section (e.g. .rodata), then the following should suffice:

const static int global = 123;

int main(void) {
    int *ptr = (int *)&global;
    *ptr = 456;

    // or, equivalent
    const int *ptr2 = &global;
    *(int *)ptr2 = 456;
}

You need to “cast away” the const qualifier in order for the compiler to not treat it as an error. Again, this only works if the compiler puts global into a read-only section (which is not required by the standard). If this does not cause a segmentation fault, then this means your compiler does not put all const variables in read-only sections.