0

When I do the following-

      const int temp=10;
      int *ptr= &temp;
      *ptr=100;

Doing this I am able to dereference a pointer to a CONST int. A const data variable is stored in .rodata which is READ ONLY MEMORY.

How am I able to write to that section? Why does it not fail?

PS. I only get a compile time warning: initialization discards 'const' qualifier from pointer to target type

Anurag
  • 651
  • 4
  • 18
  • `int *ptr = &temp;` is a constraint violation. If the compiler doesn't complain then figure out how to invoke the compiler properly – M.M May 06 '16 at 04:49
  • That's because of flexibility you get in C/C++ while working with memory. If you are sure of what you are doing then this flexibility will be of great use to you else expect some segmentation faults. However, compiler is doing its good job of alerting/warning you of such flexibility. – sameerkn May 06 '16 at 04:52

1 Answers1

3

Are you sure that it is in .rodata? This code

const int temp = 10;
int main(void) {
    int *ptr = &temp;
    *ptr = 100;
}

does crash on Linux, GCC 5.2.1; nm shows the symbol temp existing in .rodata.

However,

int main() {
    const int temp = 10;
    int *ptr = &temp;
    *ptr = 100;
}

does not crash, because the variable has automatic storage duration and it is allocated on stack instead of it residing in read-only pages of .rodata section.


Also C11 draft n1570, 6.7.3 paragraph 6:

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. [...]

And of course undefined behaviour means:

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

So indeed anything can happen, and even though your program does not crash on this, it is still wrong.


In any case, you got the warning. Whenever a C compiler gives a warning, you as a programmer should take it as an error (even by explicitly setting the -Werror) because they really are; only there is lots of old code which relies upon certain bad behaviour that these things that really actually are errors, cannot be made true errors.

Note that the C standard does not say that the int *ptr = &temp; is wrong - it is perfectly valid C as such, and only whenever you attempt to change temp via this ptr the undefined behaviour occur.