What part of dereferencing NULL pointers causes undesired behavior?

前端 未结 16 971
长情又很酷
长情又很酷 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 07:06

    That depends on the declaration of anotherfunc()

    someObj * b;
    anotherObj * c;
    b = NULL;
    c->anotherfunc(*b); 
    

    If anotherfunc() accepts a reference to b then you have not de-referenceed b, you have just converted it into a reference. If on the other hand it is a value parameter then a copy constructor will be invoked and then you have de-referenced it.

    Weather it will crash will depend on many factors (like if it has members). But the act of de-referencing on a NULL is undefined so it has the option of working on your compiler.

    As for the first option of calling a method on a NULL pointer.
    This also is undefined behavior. Weather it crashes will depend on the compiler and OS. But it is perfectly valid to not crash (the behavior is undefined).

    A lot of confusion is derived because people refer to the * in *b as de-reference operator. This may be its common name but in the standard it is the 'unary * operator' and it is defined as:

    5.3.1

    The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points.

    So the 'unary * operator' returns a reference to the object that was pointed at by the pointer it was applied to. (No de-referencing has happened at this point).

提交回复
热议问题