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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With