问题
Does the following snippet compile/execute the block in the if-statement?
int* pointer = NULL;
int deref = *pointer;
if(deref == NULL){
// will execute?
}
Since the pointer
variable contains NULL does the dereference of this pointer variable also return NULL or will this result in a runtime error?
回答1:
The result is "undefined behaviour", which may or may not trigger a runtime error, and should in any case always be avoided.
回答2:
Once you set:
int* pointer = NULL;
pointer points to nothing. Now when you write this:
int deref = *pointer;
deref will try to access what pointer points to, which will lead to an undefined behaviour like segmentation fault.
I hope this explains.
回答3:
The current answers addressed the UB very well. However, I want to add something. If you run this code:
if(0==NULL){
std::cout << "True";
}
It will prints True
. So if dereferencing a null pointer on your specific environment leads to returning 0
(which is not a steady case. It is UB), the part inside your if statement will execute.
I just wanted to clarify why it is working on some machines. However, that does not change anything about the fact that it is UB.
来源:https://stackoverflow.com/questions/39608081/is-a-null-pointers-dereference-also-equals-null