Access null pointer is not generating error

8

Testing the code below, I noticed strange behavior. It is working when it should not. The correct thing, in my view, was to give a segmentation fault and abort, but it looks like the compiler is doing some magic to fix the code.

What happens?

#include <iostream>

using namespace std;

class test{
public:
    void pa(){
    cout << "NULL????" << endl;
    }
};

int main()
{
    test * t = nullptr;
    t->pa();
    cout << "Hello world!" << endl;
    return 0;
}

Is working correctly and generating output:

NULL????
Hello world!

The parameters for the compilation are as follows:

g++ -Weffc++ -pedantic -Wextra -Wall -std=c++11 -pg -m64 -g -fexceptions -g  -c main.cpp -o obj/Debug/main.o
g++  -o bin/Debug/teste obj/Debug/main.o  -pg -m64
    
asked by anonymous 09.08.2016 / 17:37

1 answer

8

The methods are actually normal functions that have a hidden parameter that is a reference to the instance you are using (it is this ). In case there is no instance whatsoever. No problem, the argument to be passed will be a null. But the function can be called, it has nothing to prevent because the function belongs to that class, the compiler knows that it exists. Something like this:

void pa(test * this) {

We can understand that basically all methods are static, what sets apart is just that hidden parameter, so they can be accessed in all circumstances (actually virtual methods can not because there is an indirection and would have to access the vtable that somehow is a member of the object state.

The problem would occur if within the function it tried to access some state member of the instance, implicitly or explicitly through this . Then I would need to access the data somewhere in memory and it could not be null.

It works because it is not a technical impediment, but it is conceptually wrong, it is an "undefined behavior", there are no guarantees that it will always work on all platforms, so it is best to avoid this type of call.

This no longer works:

#include <iostream>
using namespace std;

class test {
    int x = 0;
public:
    void pa() {
        cout << x << "NULL????" << endl;
    }
};

int main() {
    test * t = nullptr;
    t->pa();
    cout << "Hello world!" << endl;
    return 0;
}

See not running on ideone .

The method is "compiled" like this:

void pa(teste *this) {
    cout << this.x << "NULL????" << endl;
}

And beneath the cloths the call would be:

pa(&t); //lembrando que t é nulo

Notice why the error occurs? Calling the function is not a problem, accessing the parameter this is.

    
09.08.2016 / 18:14