Is it legal to compare dangling pointers?

后端 未结 3 527
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 11:35

Is it legal to compare dangling pointers?

int *p, *q;
{
    int a;
    p = &a;
}
{
    int b;
    q = &b;
}
std::cout << (p == q) << \'\\         


        
3条回答
  •  抹茶落季
    2020-11-28 12:19

    The pointers contain the addresses of the variables they reference. The addresses are valid even when the variables that used to be stored there are released / destroyed / unavailable. As long as you don't try to use the values at those addresses you are safe, meaning *p and *q will be undefined.

    Obviously the result is implementation defined, therefore this code example can be used to study the features of your compiler if one doesn't want to dig into to assembly code.

    Whether this is a meaningful practice is totally different discussion.

提交回复
热议问题