What part of dereferencing NULL pointers causes undesired behavior?

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

    You are wandering in undefined territories.

    You can think of calling a member function like calling a regular function with the additional, implicit this pointer argument. The function call itself is just putting the arguments in place according to call convention and jumping to a memory address.

    So just calling a member function on a NULL object pointer does not necassarily cause a crash (unless it is a virtual function). You get invalid memory access crashes only when you try to access the object's member variables or vtable.

    In case #2 you may or may not get an immediate crash, depending on how anotherfunc is declared. If it takes someObj by value, then you're indirecting NULL in the function call itself, resulting in a crash. If it takes someObj by reference, usually nothing happens since references are implemented using pointers under the hood and the actual indirection is postponed until you try to access member data.

提交回复
热议问题