Accessing class members on a NULL pointer

后端 未结 8 1602
孤城傲影
孤城傲影 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条回答
  •  -上瘾入骨i
    2020-11-22 14:54

    a) It works because it does not dereference anything through the implicit "this" pointer. As soon as you do that, boom. I'm not 100% sure, but I think null pointer dereferences are done by RW protecting first 1K of memory space, so there is a small chance of nullreferencing not getting caught if you only dereference it past 1K line (ie. some instance variable that would get allocated very far, like:

     class A {
         char foo[2048];
         int i;
     }
    

    then a->i would possibly be uncaught when A is null.

    b) Nowhere, you only declared a pointer, which is allocated on main():s stack.

提交回复
热议问题