问题
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.
回答1:
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.
回答2:
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.
回答3:
In your first code, p
was pointing to some undefined memory. Luckily it was a writable memory region. It may seem to have worked, but the C++ standard, I and everyone here on SO guarantees you, that bad things will surely happen.
int main()
{
int *p; //it may even point to the first variable on the main() stack, who knows?...
int x = 2;
*p = x;
cout << *p;
}
The Second failed instantly because, you attempted an int
load (read) operation on the data at address 0
... Whose location in real life quite frankly, undefined. The offset for the read may be memory address 0+4
, or memory address 0-4
.... Again who knows.
Never use uninitialized pointers!
来源:https://stackoverflow.com/questions/36962226/why-can-you-assign-an-integer-value-to-an-uninitialized-pointer