What part of dereferencing NULL pointers causes undesired behavior?

前端 未结 16 793
长情又很酷
长情又很酷 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:12

    I agree with Buck, in that in many cases it would be nice if calling a instance function on null resulted in null. However, I don't think that it should be the default. Instead there should be another operator (I'll leave what that is up to someone else, but let's say it's ->>).

    One issue in C++, for instance, is that not all return types can be null anyway, such as int. So a call to a->>length() would be difficult to know what to return when a itself was null.

    Other languages where everything is a reference type, you would not have this problem.

    Finally, Buck, what everyone else is saying is the way things are, especially for the C++ language: Dereferencing is a mechanical operation in most languages: It must return something of the same type and null is typically stored as zero. Older systems would just crash when you tried to resolve zero, newer ones would recognize the special nature of the value when the error occured.

    Also, these lower level languages cannot represent null as an integer (or other basic data types), so you could not in general deference null as null in all cases.

提交回复
热议问题