Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

c++ - Is it undefined behavior to dereference a dangling pointer?

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;
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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):

...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:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...