paper.plane
paper.plane

Reputation: 1197

Unexpected output instead of runtime error

It might be obvious for who knows the background magic, but I could not understand how below code is giving correct output. I expected a runtime error. Please help.

class a
{
  public:
    void print()
    {
        cout<<"Hello\n"<<endl;
        int d = 100;
        cout<<d<<endl;
    }

    int val;
};


int main()
{
   a* ptr;

   ptr->print();

   return SUCCESS;
}

OUTPUT is as below :

Hello

100

Upvotes: 0

Views: 130

Answers (2)

Zalman Stern
Zalman Stern

Reputation: 3191

a::print is a not a virtual method, hence it is just a normal function that has an extra argument to receive the this pointer. Since the method never uses the this pointer, the fact that it is uninitialized doesn't turn into a memory access error or other failure. Declaring a::print static will still compile in this case since it doesn't use the this pointer. Declaring a::print virtual or accessing this inside the method will likely lead to the program crashing, at least under some circumstances.

The behavior is still undefined and it is an ill-formed program, but as it stands now it is very likely to work deterministically on most systems. In general C++ does not give runtime errors for such cases, but if you compile with e.g. "clang++ -Wall" a warning indicating the uninitialized variable will be given. (And there are tools such as clang's asan which will go further in diagnosing such errors.)

Upvotes: 4

myaut
myaut

Reputation: 11504

There is no magic - your code has undefined behavior. In your code you do not access ptr which is implicitly passed to print() as this pointer, that is why no error happen.

It may happen in several other cases:

  • Accessing fields of a instance. It will require to read memory *(this + field_offset) which will cause runtime error.

  • Accessing virtual methods. Implementations known to me use vtable to do that, which is usually stored as first pointer in object space, so pointer to vtable would be same as this, so: vtable = *this

  • Other cases, depending on compiler and platform

NOTE: type conversion is omitted from examples with this

Upvotes: 5

Related Questions