What part of dereferencing NULL pointers causes undesired behavior?

前端 未结 16 795
长情又很酷
长情又很酷 2021-01-22 06:41

I am curious as to what part of the dereferencing a NULL ptr causes undesired behavior. Example:

//  #1
someObj * a;
a = NULL;
(*a).somefunc();   // crash, dere         


        
16条回答
  •  盖世英雄少女心
    2021-01-22 06:54

    The second example is also undefined behavior, yes. You are only allowed to call member functions on a valid object. And a null pointer does not point to a valid object.

    The reason why it appears to work is that member functions are typically implemented roughly like this:

    void anotherfunc(anotherObj* this, someObj& arg);
    

    That is, the "this" pointer is basically passed to the function as a separate argument. So while calling the function, the compiler doesn't check that the this pointer is valid, it just passes it to the function.

    It is still undefined behavior though. The compiler isn't guaranteed to let this work.

提交回复
热议问题