Undefined behaviour of const

前端 未结 4 762
灰色年华
灰色年华 2020-12-10 09:42

I never thought I will be going to ask this question but I have no idea why this happens.

const int a = 3; 
int *ptr;
ptr = (int*)( &a );
printf( \"A=%d\         


        
相关标签:
4条回答
  • 2020-12-10 09:59

    Modifying a const variable through a non-const pointer results in undefined behavior. Most ikely the optimizer is substituting the original value in this line:

    printf( "A=%d\n", a );
    

    Look at the disassembly to verify this.

    The C Standard, subclause 6.7.3, paragraph 6 [ISO/IEC 9899:2011], states: 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.

    0 讨论(0)
  • 2020-12-10 10:04

    The problem is that the type of ptr is "pointer to int" not "pointer to const int". You are then casting the address of 'a' (a const int) to be of type "pointer to int" and storing that address in ptr. The effect of this is that you are casting away the const-ness of a const variable.

    This results in undefined behavior so your results may vary from compiler to compiler.

    It is possible for the compiler to store 'a' in program ROM since it knows 'a' is a const value that can never be changed. When you lie to the compiler and cast away the const-ness of 'a' so that you can modify it through ptr, it may be invalid for ptr to actually modify the value of 'a' since that data may be stored in program ROM. Instead of giving you a crash, this compiler this time decided to point ptr to a different location with a different value this time. But anything could have happened since this behavior is undefined.

    0 讨论(0)
  • 2020-12-10 10:05

    The optimizer can determine that a is a constant value, and replace any reference to it with the literal 3. That explains what you see, although there's no guarantee that's what's actually happening. You'd need to study the generated assembly output for that.

    0 讨论(0)
  • 2020-12-10 10:10

    In fact your program invokes undefined behavior because of two reasons:
    1.You are printing an address with wrong specifier %d. Correct specifier for that is %p.
    2.You are modifying a variable with const specifier.

    If the behavior is undefined then anything could happen. You may get either expected or unexpected result.
    Standard says about it;

    3.4.3 undefined behavior

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

    0 讨论(0)
提交回复
热议问题