Accessing class members on a NULL pointer

后端 未结 8 1348
孤城傲影
孤城傲影 2020-11-22 14:11

I was experimenting with C++ and found the below code as very strange.

class Foo{
public:
    virtual void say_virtual_hi(){
        std::cout << \"Vi         


        
8条回答
  •  醉酒成梦
    2020-11-22 15:02

    It is undefined behaviour. But most of compilers made instructions which will handle this situation correctly if you don't accessing to member variables and virtual table.

    let see disassembly in visual studio for understand what happens

       Foo* foo = 0;
    004114BE  mov         dword ptr [foo],0 
        foo->say_hi(); // works well
    004114C5  mov         ecx,dword ptr [foo] 
    004114C8  call        Foo::say_hi (411091h) 
        foo->say_virtual_hi(); // will crash the app
    004114CD  mov         eax,dword ptr [foo] 
    004114D0  mov         edx,dword ptr [eax] 
    004114D2  mov         esi,esp 
    004114D4  mov         ecx,dword ptr [foo] 
    004114D7  mov         eax,dword ptr [edx] 
    004114D9  call        eax  
    

    as you can see Foo:say_hi called as usual function but with this in ecx register. For simplify you can assume that this passed as implicit parameter which we never use in your example.
    But in second case we calculating adress of function due virtual table - due foo addres and gets core.

提交回复
热议问题