What part of dereferencing NULL pointers causes undesired behavior?

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

    you need to know more about anotherfunc() to tell what will happen when you pass it null. it might be fine, it might crash, depends on the code.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-22 07:14

    Tom's comment is correct, I did not initialize correctly therefore the question is ambiguous at best yet most everyone directly answered my question, I unwittingly submitted the question while not logged in (sorry I'm new to stackoverflow) so can someone with editing powers update the OP?

    //  #2
    someObj * b;
    anotherObj * c = new anotherObj();        //initialize c
    b = NULL;
    c->anotherfunc(*b);   // *b is in question not the c dereference
    
    0 讨论(0)
  • 2021-01-22 07:16

    It would still cause a crash, but that's not necessarily undesired behaviour. Part of the usefulness of NULL is that, on most platforms, it points to memory that is explicitly inaccessible to your application, and causes a segmentation fault (or access violation) the very moment you try to dereference it.

    Its purpose is to explicitly mark the contents of pointers as invalid.

    0 讨论(0)
提交回复
热议问题