Is it undefined behavior to dereference a dangling pointer?

后端 未结 4 1955
夕颜
夕颜 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:27

    So first of all according to 3.7.3 Automatic storage duration storage of your object is released:

    Block-scope variables explicitly declared register or not explicitly declared static or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.

    And from 3.8 Object lifetime

    Before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any pointer that refers to the storage location where the object will be or was located may be used but only in limited ways

    so dereferencing pointer to variable which storage released leads to UB

提交回复
热议问题