Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 752
Arvin Wong Avatar asked Jan 06 '23 04:01

Arvin Wong


2 Answers

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.

like image 191
R Sahu Avatar answered Jan 25 '23 19:01

R Sahu


Never use an uninitialized pointer or dereference a null pointer, what you have done is undefined behaviour, anything in the world could happen. Your code actualy working and behaving ‘reasonably’ is pure luck.

As to why your code acted the way it did, it is likely due to the way your compiler & machine & OS behave. Your variable declaration for p would just reserve uninitialized memory, whose value could be anything, you were just ‘lucky’ in that that value refers to a read-writable memory location. Whereas by explicitly setting it to ‘0’, it points to what your OS probably has as an unreadable & unwritable memory location, and any attempt to access it will cause your CPU to complain to your OS, which responds by killing your program. Do not rely on this behaviour it is just what probably happened, it may not occur in the future, even under the same system configuration.

like image 25
Isaac Avatar answered Jan 25 '23 19:01

Isaac