Is it undefined behavior to dereference a dangling pointer?

后端 未结 4 1951
夕颜
夕颜 2020-12-06 18:11

I can\'t find where in the standard that it says this program is undefined:

#include 

int main() 
{
    int *p;
    {
        int n = 45;
           


        
4条回答
  •  眼角桃花
    2020-12-06 18:41

    *p is a glvalue. The code cout << *p necessitates an lvalue-to-rvalue conversion. This is defined by C++14 [conv.lval].

    Point 2 lists various cases and describes the behaviour in each case. None of those apply to *p. Particularly, the last point is:

    Otherwise, the value contained in the object indicated by the glvalue is the prvalue result.

    However, *p does not indicate an object.

    In section [basic.life] are a few cases that define what lvalue-to-rvalue conversion does, beyond what is said in [conv.lval]. Those cases relate to when storage for an object has been obtained, but we are outside the object's lifetime. However they do not apply to *p because storage is released when the previous block ends.

    So, the behaviour of this code is undefined by omission: nowhere in the Standard does it define what it means to perform rvalue conversion when the lvalue does not indicate an object and does not indicate valid storage for an object.


    It can feel unsatisfactory for something to be "undefined by omission", we always like to see a concrete statement "this is undefined behaviour" to be sure we haven't overlooked something. But sometimes that is how it is.

提交回复
热议问题