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

Categories

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

c++ - Why can you assign an integer value to an uninitialized pointer

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...