accessing the nullptr data

130 views Asked by At

I ran into a problem with an uninitialised unique ptr, here is the code:

class Demo {
   public:
    Demo() {}
    void noSegFault()
    {
        std::cout << "noSegFault" << std::endl;        
    }
    void segFault() {
        std::cout << "Address of data :" << &data << std::endl;
        std::cout << "Before segfault" << std::endl;
        data = 234;
        std::cout << "After segfault" << std::endl;
    }

   private:
    int data{123};
};

int main() {
    std::unique_ptr<Demo> demoPtr{nullptr};
    if (demoPtr == nullptr) {
        std::cout << "demoPtr is null" << std::endl;
    }
    demoPtr->noSegFault();
    demoPtr->segFault();
    return 0;
}

Output:

demoPtr is null
noSegFault
Address of data :0
Before segfault

In this context, demoPtr is initialized with nullptr. I used to believe that accessing nullptr would inevitably lead to a segmentation fault. However, in this program, I can successfully call the noSegFault method and observe its output. Yet, if I attempt to access any variables of the nullptr object(invoking segFault method), a segmentation fault occurs.

So as per the output I can able to invoke the methods which doesn't use its member variables successfully without segmentation fault.Is it the expected behaviour?

godblot link: https://godbolt.org/z/G34c1jefb

0

There are 0 answers