它是未定义的行为以解引用悬空指针吗? [英] Is it undefined behavior to dereference a dangling pointer?

查看:149
本文介绍了它是未定义的行为以解引用悬空指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在标准中找不到该程序未定义的位置:

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

#include <iostream>

int main() 
{
    int *p;
    {
        int n = 45;
        p = &n;
    }
    std::cout << *p;
}

在§3.8对象生命周期中的情况似乎都不适用。

None of the cases in §3.8 object lifetime seem to apply here.

推荐答案

我不是100%肯定因为措辞,但它看起来像是由3.8 / 6我认为这种解释是正确的是因为3.8 / 5中的非规范性的例子, //未定义的行为,* pb的生命周期已经结束):

I'm not 100% sure because of the wording but it looks like this is covered by 3.8/6 (the reason I think this interpretation is correct is because of the non-normative example in 3.8/5, // undefined behavior, lifetime of *pb has ended):


...在对象的生命周期结束后,在对象占用的存储被重用或释放之前,引用原始对象的任何glvalue只有在有限的方式....程序有未定义的行为if:

...after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways....The program has undefined behavior if:

然后第一个项目符号是罪魁祸首: code>一个左值到值的转换(4.1)应用于这样的glvalue,:这种转换必须发生在调用 < 或最后在读取整数值以在 ostream 代码中进行格式化的地方。

Then the first bullet is the culprit: an lvalue-to-rvalue conversion (4.1) is applied to such a glvalue,: This conversion has to happen either at the point of call to operator<< or finally at the point where the integral value is read for formatting within ostream code.

这篇关于它是未定义的行为以解引用悬空指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆