Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When I do this, it prints out "2" perfectly.

int main()
{
    int *p;
    int x = 2;

    *p = x;

    cout << *p;

}

But when I first initialized *p to be null, the program crashes.

int main()
{
    int *p=0;
    int x = 2;

    *p = x;

     cout << *p;

}

I want to ask what does the first program even successfully run in the first place, why can a value be assigned to an uninitialized pointer?

[EDIT] My question is actually related to this past exam question that I got. You can tick more than one answer and it seems (b) & (c) both are correct. But now I know whether (c) works is purely due to luck.

enter image description here

See Question&Answers more detail:os

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

1 Answer

The first program is subject to undefined behavior. It seems like it works but, unfortunately, seemingly sane behavior is also undefined behavior.

Don't count on a program to work correctly all the time if it dereferences an uninitialized pointer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...