Namhee Kim
Namhee Kim

Reputation: 11

I try to access the value of a null pointer in win32 application, but no access violation occurs

I wrote sample code that should cause access violation, but it does not. I think the exception should occur in GetSession1(), GetSession2() function for return *m_pObj, but it does not. Why is that?

Header file

class CSession
{
    public:
        CSession() {};
        ~CSession() {};
        CSession(const CSession& rhs) {};
    private:
        long m_lUSN;
};

class CTest
{
    public:
        CSession* m_pObj;
        CSession& GetSesstion1() { m_pObj = NULL; return *m_pObj; }
        CSession GetSesstion2(); { m_pObj = NULL; return *m_pObj; }
};

Cpp file

int _tmain(int argc, _TCHAR* argv[])
{
    CTest test;
    CSession Session2 = test.GetSesstion1();
    CSession Session3 = test.GetSesstion2();
    return 0;
};

Upvotes: 1

Views: 79

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597196

You wrote constructors that do not do anything, so you are not actually trying to access m_lUSN when located at a NULL address, thus you don't get any AVs. If you change your CSession() copy constructor to copy the value of rhs.m_lUSN to this->m_lUSN, or add public getter/setter methods so _tmain() can read/set the m_lUSN value, you will start seeing AVs occur from the objects returned by GetSesstion(1|2)().

Upvotes: 2

vsoftco
vsoftco

Reputation: 56567

Dereferencing a null pointer is undefined behaviour (a more "serious" link here: Why dereferencing a null pointer is undefined behaviour?). Your program may crash, or may do whatever it wants. The C++ standard doesn't mandate to have an "access violation".

Undefined behaviour (UB) is bad, and you cannot rely on a compiler to always catch it. For example, the code below makes it clear why UB is bad:

#include <iostream>

int main()
{
    int *p = nullptr;
    int  q = *p;
    //std::cout << q;
}

On my machine, I get no warning whatsoever, the code compiles and runs just fine. If I un-comment the std::cout line, BANG, it crashes. That's because probably the compiler optimized out the dereferencing of the null pointer, however cannot optimize it out when trying to use q. That's what's probably happening in your code, but again, it is UB and the fact that the program runs should not give you any reassurance.

Upvotes: 6

Related Questions