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.
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