-2

Is it possible to change the value of const global or extern global variable? via pointer?

you can change the value of const local variable.

selva
  • 97
  • 1
  • 5
  • 4
    It *is* constant, attempting to modify it (through pointers or some other means) will lead to *undefined behavior*. – Some programmer dude Dec 28 '13 at 11:20
  • 6
    What do you think the keyword `const` means? – Ed Heal Dec 28 '13 at 11:21
  • 1
    Mr.Ed Heal, you can change the value of const local variable. don't you know? – selva Dec 28 '13 at 11:22
  • @selva - really. demonstrate that with http://codepad.org – Ed Heal Dec 28 '13 at 11:26
  • @ED Heal:use in code::blocks and see the result #include int main(void) { int const index = 10; int *ptr = &index; printf("%d\n",index); *ptr = 20; printf("%d\n",index); return 1; } – selva Dec 28 '13 at 11:30
  • @salva- you are on shaky ground(undefined behavior). The compiler could optimise it away – Ed Heal Dec 28 '13 at 11:33
  • @ED HEAL: try the following code in codepad.org – selva Dec 28 '13 at 11:42
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/44053/discussion-between-selva-and-ed-heal) – selva Dec 28 '13 at 11:46
  • in windows it generates memory exception, In my experience you can't change global constant values. – vivek Jun 07 '16 at 12:01
  • @selva is right you can overwrite a local `const` variable see [C - How can a pointer overwrite a local const block of memory but not the global const block of memory?](https://stackoverflow.com/questions/64650095/c-how-can-a-pointer-overwrite-a-local-const-block-of-memory-but-not-the-global) – Ayush Oct 12 '21 at 10:05

8 Answers8

3

Although it may be possible to appear to change the value of a const object in some C implementations, this appearance may be an illusion, and it is difficult to do in a controlled way because:

  • The C standard does not define the behavior when an attempt is made to modify an object defined with const.
  • The modification might appear to work in that it causes some uses of the object to change but not others. For example, a compiler may build the value of a const object into other expressions, so that the initialization of x in const int a = 10; int x = 2*a; initializes x to 20 without referring to a at all. It can happen that some uses of a refer to the memory allocated for it and use the changed value, if you manage to change it, while other uses of a in the same program use the original value in a built-in way. Obviously, this results in a very confusing program.
  • A modification might “work” in one C implementation but fail in another C implementation because the two implementations manage const objects in different ways.
  • A modification might appear to work in your program but fail when you change the source code in apparently unrelated ways, such as inserting additional calculations that require the compiler to save some temporary values to the stack. Your program might also fail when you change compiler options, especially when you enable optimization.

In many C implementations, constant global data is stored in an area of memory that is marked read-only. Attempting to modify it results in an exception that usually terminates your program. It may be possible to ask the operating system to change this protection and then modify memory. However, doing so risks side effects that come from the compiler assuming that constant data will not change.

When you are able to modify an automatic object (such as one defined instead a function body) but not a static object (such as one defined outside any function), it may be because the static object is kept with constant global data, which is marked read-only, but automatic objects are kept on the stack. The stack contains a mixture of different things, and it is not possible on today’s processors to mark small parts of the stack read-only while leaving other parts writeable. Thus, you may have the physical access to modify const automatic objects. However, you still do not have the license from the C standard to do so; the behavior is undefined, and there may be hidden side effects that will break your program.


On a separate note, const does not always mean an object is constant. When an object is defined with const, the C standard does not define the behavior of attempting to modify it. However, it is possible to add const to a pointer and remove it later. For example, this is legal code:

int a = 3;
const int *b = &a;
int *c = (int *) b;
*c = 4;

This behavior is needed because the C language was originally designed without const, so its semantics are not designed to accommodate it, and there are some circumstances where things would not work correctly if const were always enforced.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • nice explanation. so from your point I cant try to change the const value,no matter where is it declare? – selva Dec 28 '13 at 11:57
  • @selva: You **can** try, in the sense you can write code that attempts it. You **may not** do so if you want to conform to the C standard. If you try, your code might not work, even if it initially appears to work. – Eric Postpischil Dec 28 '13 at 12:08
2

C11: 6.7.3 Type qualifiers:

If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.

In other words you can say that a const-qualified object is non-modifiable

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
2

I'm guessing it will depend. For example, for this program

#include <stdio.h>

const int val = 12345;

int main(void)
{
    printf("%d\n", val);

    int *tmp = (int *)&val;
    *tmp = 678;

    printf("%d\n", val);
    return 0;
}

the program (compiled using gcc on Linux) produces a segmentation fault. But if the 'const' line is moved inside the main function and made a local variable instead, it does seem to work (without any optimizations enabled).

Upon inspection of the executable with objdump, the variable val is in a section called .rodata, causing a segmentation fault when the program tries to change the memory somehow.

brm
  • 3,706
  • 1
  • 14
  • 14
1

You can still try to use the mprotect function to change the data section to RW instead of RO.

http://linux.die.net/man/2/mprotect

See Self modifying code always segmentation faults on Linux

Since it's your program's own segment, you don't need any privilege. This code may work :

#include <stdio.h>
#include <sys/mman.h>

const int c = 1;

int main(int argc, char *argv[])
{
    if(mprotect(&c, sizeof(int), PROT_READ | PROT_WRITE) == 0) c = 5;
    printf("%d\n", c);
    return 0;
}
Community
  • 1
  • 1
Josselin Poiret
  • 508
  • 3
  • 10
0

Const variables can´t be changed, that´s why they are const. Other variables can be changed, and you won´t need a pointer if you have access to the variable itself

deviantfan
  • 11,268
  • 3
  • 32
  • 49
0

A constant's value can not be changed that is why it is called constant.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
0

The question doesn't make sense: Variables don't have values, only objects and expressions do.

You cannot change the value of a constant object.

However, you can have a variable of some suitable sort of "constant reference" type which evaluates to different things:

int a = 10;

const int * const b = &a;

int main()
{
    print(b);
    *a = 20;
    print(b);
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

Yes, you can:

#include <stdio.h>

const volatile int global = 10;

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

    printf("Initial value of global : %d \n", global);
    *ptr = 100;
    printf("Modified value of global: %d \n", global);
    return 0;
}

It might work due to volatile (take a look)

But as suggested by others, don't do it

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • 3
    that is great. i wont use it – selva Dec 28 '13 at 11:40
  • Compiling this with GCC 4.2.1 (Apple build 5666) with default options on Mac OS X 10.6.8 and executing the result yields a bus error. One should not confuse “This happened to work in one case I tried with one C implementation on one system” with “This is supported in C”. In fact, this **almost** works; the `volatile` does tell the C implementation that the value of `global` may change. However, it **does not** say that you may change the value in plain C. It says the value may changed by some means unknown to the C implementation. So you **could** write other code to modify it, perhaps by… – Eric Postpischil Dec 28 '13 at 13:26
  • … modifying the memory protection on the page where `global` resides, then modifying it in C. If that were done correctly, it could be valid, completely defined code based on a combination of the C standard and the specification of the memory protection features of the host system (e.g., the documentation of the `mprotect` call used to change memory protection). However, this code, as it stands, does not make the modification correctly. – Eric Postpischil Dec 28 '13 at 13:29