Code runs without pointer being initialized [duplicate] - c++

This question already has answers here:
When does invoking a member function on a null instance result in undefined behavior?
(2 answers)
Closed 1 year ago.
I was given the following as an interview question:
class A
{
public:
void fun()
{
std::cout << "fun" << std::endl;
}
};
A* a = NULL;
a->fun();
What will happen when this code is executed, and why?
See also:
When does invoking a member function on a null instance result in undefined behavior?

It's undefined behavior, so anything might happen.
A possible result would be that it just prints "fun" since the method doesn't access any member variables of the object it is called on (the memory where the object supposedly lives doesn't need to be accessed, so access violations don't necessarily occur).

By the standard, this is undefined behavior and therefore a very bad thing. In reality of most programming platforms (across both X86 and several other architectures) this will run fine.
Why? Consider how class functions are implemented in C++. This isn't a virtual function, therefor this can be a static call to a known address.
In x86 assembly, we can see this as
mov A, 0
mov ecx, A
call a__fun
since a__fun requires no instance data, even though it receives a null this pointer, nothing will happen.
Still shitty code and any compiler will scream, but it can run.

The most likely behavior, on most modern computers, is that it will run, and print "fun", because:
C++ doesn't check whether the pointer is NULL before calling the function
fun() is not virtual, so there's no need to refer to a vtable to call fun()
fun() never access any member variables in A so it doesn't need to dereference
the null this pointer.

We can't know what will. Everything can happen, because the program exposes undefined behavior. See Does invoking a member function on a null instance cause undefined behavior?.

I have tried multiple times,all the time output is coming "fun" this is because function fun is independent of instance a. while calling a->fun(); a points to 0 so this is undefined behavior but in most of the compilers there should be no crash.

Three points might help:
1) All Functions are stored in code or text section.
2) Non Virtual functions are resolved at complie time.
3) While calling to member functions of class, we pass current object as this pointer to that function.
Coming to your question , here fun() function is already in memory(code section / text section).
As function fun() is non virtual , it will be resolved at complie time (i.e, for this line it will jump to instruction X at code section with this pointer as NULL).
As no member variable and no virtual function are used/called in fun() function, it is working fine.

Related

Method is still working after moving smart pointer ownership [duplicate]

This question already has answers here:
When does invoking a member function on a null instance result in undefined behavior?
(2 answers)
Closed 1 year ago.
I was given the following as an interview question:
class A
{
public:
void fun()
{
std::cout << "fun" << std::endl;
}
};
A* a = NULL;
a->fun();
What will happen when this code is executed, and why?
See also:
When does invoking a member function on a null instance result in undefined behavior?
It's undefined behavior, so anything might happen.
A possible result would be that it just prints "fun" since the method doesn't access any member variables of the object it is called on (the memory where the object supposedly lives doesn't need to be accessed, so access violations don't necessarily occur).
By the standard, this is undefined behavior and therefore a very bad thing. In reality of most programming platforms (across both X86 and several other architectures) this will run fine.
Why? Consider how class functions are implemented in C++. This isn't a virtual function, therefor this can be a static call to a known address.
In x86 assembly, we can see this as
mov A, 0
mov ecx, A
call a__fun
since a__fun requires no instance data, even though it receives a null this pointer, nothing will happen.
Still shitty code and any compiler will scream, but it can run.
The most likely behavior, on most modern computers, is that it will run, and print "fun", because:
C++ doesn't check whether the pointer is NULL before calling the function
fun() is not virtual, so there's no need to refer to a vtable to call fun()
fun() never access any member variables in A so it doesn't need to dereference
the null this pointer.
We can't know what will. Everything can happen, because the program exposes undefined behavior. See Does invoking a member function on a null instance cause undefined behavior?.
I have tried multiple times,all the time output is coming "fun" this is because function fun is independent of instance a. while calling a->fun(); a points to 0 so this is undefined behavior but in most of the compilers there should be no crash.
Three points might help:
1) All Functions are stored in code or text section.
2) Non Virtual functions are resolved at complie time.
3) While calling to member functions of class, we pass current object as this pointer to that function.
Coming to your question , here fun() function is already in memory(code section / text section).
As function fun() is non virtual , it will be resolved at complie time (i.e, for this line it will jump to instruction X at code section with this pointer as NULL).
As no member variable and no virtual function are used/called in fun() function, it is working fine.

throwing exception but still able to call member function [duplicate]

This question already has answers here:
When does invoking a member function on a null instance result in undefined behavior?
(2 answers)
Closed 1 year ago.
I was given the following as an interview question:
class A
{
public:
void fun()
{
std::cout << "fun" << std::endl;
}
};
A* a = NULL;
a->fun();
What will happen when this code is executed, and why?
See also:
When does invoking a member function on a null instance result in undefined behavior?
It's undefined behavior, so anything might happen.
A possible result would be that it just prints "fun" since the method doesn't access any member variables of the object it is called on (the memory where the object supposedly lives doesn't need to be accessed, so access violations don't necessarily occur).
By the standard, this is undefined behavior and therefore a very bad thing. In reality of most programming platforms (across both X86 and several other architectures) this will run fine.
Why? Consider how class functions are implemented in C++. This isn't a virtual function, therefor this can be a static call to a known address.
In x86 assembly, we can see this as
mov A, 0
mov ecx, A
call a__fun
since a__fun requires no instance data, even though it receives a null this pointer, nothing will happen.
Still shitty code and any compiler will scream, but it can run.
The most likely behavior, on most modern computers, is that it will run, and print "fun", because:
C++ doesn't check whether the pointer is NULL before calling the function
fun() is not virtual, so there's no need to refer to a vtable to call fun()
fun() never access any member variables in A so it doesn't need to dereference
the null this pointer.
We can't know what will. Everything can happen, because the program exposes undefined behavior. See Does invoking a member function on a null instance cause undefined behavior?.
I have tried multiple times,all the time output is coming "fun" this is because function fun is independent of instance a. while calling a->fun(); a points to 0 so this is undefined behavior but in most of the compilers there should be no crash.
Three points might help:
1) All Functions are stored in code or text section.
2) Non Virtual functions are resolved at complie time.
3) While calling to member functions of class, we pass current object as this pointer to that function.
Coming to your question , here fun() function is already in memory(code section / text section).
As function fun() is non virtual , it will be resolved at complie time (i.e, for this line it will jump to instruction X at code section with this pointer as NULL).
As no member variable and no virtual function are used/called in fun() function, it is working fine.

Is calling a nonvirtual member function on a non-constructed "object" well-defined? [duplicate]

This question already has answers here:
What will happen when I call a member function on a NULL object pointer? [duplicate]
(6 answers)
When does invoking a member function on a null instance result in undefined behavior?
(2 answers)
Closed 9 years ago.
Inside a constructor, calling non-virtual member functions is permitted.
Does from this fact follow that the following piece of code is well-defined?
struct A {
void foo { std::cout << "Hi there! My address is: " << this; }
};
A * a = nullptr;
a->foo ();
Answer?
With the help of some links given in the comments, and the links given in the linked pages, I now think that the answer can be found e.g. in
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3035.pdf
§3.8 par. 5, p. 66:
"Before the lifetime of an object has started but after the storage which the object will occupy has been allocated ... [t]he program has undefined behavior
if [...] the pointer is used to access a non-static data member or call a non-static member function of the object"
Then it should be even more undefined to call a member function if storage has not been allocated at all.
I guess one important reason why it is a good idea to make it undefined is explained here: https://stackoverflow.com/a/3257755/1419315
That code is undefined behavior.
Note that inside the constructor you can also call virtual member function.
The somewhat tricky part is calling virtual member function during member initialization before the constructor code begins. Still valid but it's not obvious what happens (the point is that until the constructor code begins the object isn't considered yet an instance of its class and virtual member functions get dispatched to the base class).
Some compilers emit a warning if you use this in the member initialization list exactly because the this pointer will behave strangely at that point (it will start behave normally only after the start of the constructor).
The code apparently works because most compilers use the VMT approach for method dispatching but the VMT is not needed to call a non-virtual method and thus if the method code doesn't dereference in any way this then things seems to "work". However the fact that the code seems to work in an implementation (or even in every implementation for that matter) still doesn't make it legal C++ code.

C++ Call a non-virtual non-static method from a null pointer, without accessing members : is this guaranteed to work? [duplicate]

This question already has answers here:
Is it legal/well-defined C++ to call a non-static method that doesn't access members through a null pointer?
(5 answers)
When does invoking a member function on a null instance result in undefined behavior?
(2 answers)
Closed 8 years ago.
Can I call a non-static, non-virtual method of a class from a null pointer? The member function would then test if this==nullptr, and return immediately if it's true.
I know it will work in most cases, but is this a guaranteed result? That way, I can ensure null pointer exceptions never happen, and avoid testing for null pointers in many places of the caller code. That's for compactness, I'm not going to do that right now, but I'm curious to know if any standard will guarantee this to work...
Thanks!
Dereferencing a nullptr is Undefined behavior. Period!
Whether it works or not on one particular implementation is irrelevant, the behavior is not guaranteed.
The standard expliticly mentions dereferencing NULL pointer as undefined behavior. Using opearator -> dereferences the pointer to left.
So you're okay only in case if your implementation defined some behavior for the case, as it is a possibility (though I never encountered it in real life yet).
(I hope you understand that observing something is not the same as being defined.)
always avoid calling a null pointer,
you would usually end up with a core dump
There are interesting answers here:
When does invoking a member function on a null instance result in undefined behavior?
Also, the standard gives no hint about the mechanism for calling member virtual functions. It is usually done by just passing 'this' as a hidden function argument, which will in practice not dereference the pointer and work. However, it seems possible to implement even non-virtual function with a vtable, which in this case would crash.
Interestingly, a Microsoft function relies on this behavior :)
http://msdn.microsoft.com/en-us/library/d64ehwhz%28v=vs.80%29.aspx

-> operator on null objects

According to C++ Standard, it's perfectly acceptable to do this:
class P
{
void Method() {}
};
...
P* p = NULL;
p->Method();
However, a slight change to this:
class P
{
virtual void Method() {}
};
...
P* p = NULL;
p->Method();
produces an access violation when compiled with Visual Studio 2005.
As far as I understand, this is caused by some quirk in Microsoft's compiler implementation and not by my sheer incompetence for a change, so the questions are:
1) Does this behavior persist in more recent versions of VS?
2) Are there any, I don't know, compiler settings that prevent this access violation?
According to C++ Standard, it's perfectly acceptable to do this
No it is not!
Dereferencing a NULL pointer is Undefined Behavior as per the C++ Standard.[#1]
However, If you do not access any members inside a non virtual member function it will most likely work on every implementation because for a non virtual member function the this only needs to be derefernced for accessing members of this since there are no members being accessed inside the function hence the result.
However, just because the observable behavior is okay does not mean the program is well-formed. correct.
It still is ill-formed.
It is an invalid program nevertheless.
The second version crashes because while accessing a virtual member function, the this pointer needs to be dereferenced just even for calling the appropriate member function even if there are no members accessed within that member function.
A good read:
What's the difference between how virtual and non-virtual member functions are called?
[#1]Reference:
C++03 Standard: §1.9/4
Certain other operations are described in this International Standard as undefined (for example, the effect of dereferencing the null pointer). [Note: this International Standard imposes no requirements on the behavior of programs that contain undefined behavior. ]
As said by AIs... I'll even explain why: in many C++ implementations the this pointer is simply passed as the first "hidden" parameter of the method. So what you see as
void Method() {}
is really
void Method(P* this) {}
But for virtual methods it's more complex. The runtime needs to access the pointer to find the "real" type of P* to be able to call the "right" virtual implementation of the method. So it's something like
p->virtualTable->Method(p);
so p is always used.
First of all, neither one will even compile, because you've defined Method as private.
Assuming you make Method public, you end up with undefined behavior in both cases. Based on the typical implementation, most compilers will allow the first to "work" (for a rather loose definition of work) while the second will essentially always fail.
This is because a non-virtual member function is basically a normal function that receives an extra parameter. Inside that function, the keyword this refers to that extra parameter, which is a pointer to the class instance for which the function was invoked. If you invoke the member function via a null pointer, it mostly means that inside that function this will be a null pointer. As long as nothing in the function attempts to dereference this, chances are pretty good that you see any noticeable side effects.
A virtual function, however, is basically a function called via a pointer. In a typical implementation, any class that has one or more virtual functions (whether defined directly in that class, or inherited from a base class) will have a vtable. Each instance of that class (i.e., each object) will contain a pointer to the vtable for its class. When you try to call a virtual function via a pointer, the compiler will generate code that:
Dereferences that pointer.
Gets the vtable pointer from the proper offset in that object
dereferences the vtable pointer to get the class' vtable
looks at the proper offset in the vtable to get a pointer to the function to invoke
invokes that function
Given a null pointer, step one of that process is going to break.
I'd note for the record that this applies to virtually all C++ compilers. VC++ is far from unique in this regard. Quite the contrary -- while it's theoretically possible for a compiler to implement virtual functions (for one example) differently than this, the reality is that every compiler of which I'm aware works essentially identically for the kind of code you posted. Virtually all C++ compilers will show similar behavior given the same code -- major differences in implementation are mostly a theoretical possibility, not one you're at all likely to encounter in practice.