Is a NULL pointer's dereference also equals NULL?

倾然丶 夕夏残阳落幕 提交于 2019-12-12 13:08:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!