What part of dereferencing NULL pointers causes undesired behavior?

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

    In practice, it doesn't crash until it needs to use the NULL value. This means that you can call non-virtual functions because they are bound at compile time. It calls the function just fine and passes in a NULL this pointer. Now if you try to use any member variables then it will crash because it will try to look them up based on the this pointer passed in. You can also call other non-virtual functions by the same argument. Now if you try to use a virtual function it will immediately crash because it tries to find the vtable from the NULL pointer.

    We ran into a case like this and I had to write some example code to demonstrate to the other developers that even though it was reporting the error in 2 levels of calls to member functions it was actually a NULL pointer that was being called. The error was manifested when an actual value was used.

提交回复
热议问题