Why is it allowed to overwrite a const variable using a pointer to it using memcpy?

后端 未结 4 428
难免孤独
难免孤独 2021-01-21 04:19

Why is it allowed to change a const variable using a pointer to it with memcpy?

This code:

const int i=5;
int j = 0;
memcpy(&j, &i, sizeof(int));         


        
4条回答
  •  一向
    一向 (楼主)
    2021-01-21 04:59

    Attempt to modify the value of a const-qualified variable leads to an undefined behavior in C. You should not rely on your results, since anything can happen.

    C11 (n1570), § 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.

    Nothing force the compiler to produce a diagnostic message.

    In fact, this qualifier has not enormous effects on the machine code. A const-qualified variable does not usually reside in a read-only data segment (obviously, not in your implementation, although it could be different on an other one).

    The compiler can't tell easily what a pointer is pointing to in a given function. It is possible with some static analysis tools, which perform pointer-analysis. However, it is difficult to implement, and it would be stupid to put it in the standard.

提交回复
热议问题