Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

c++ - Does calling a method on a NULL pointer which doesn't access any data ever fail?

Will the program:

#include <stdio.h>

struct foo
{
   void blah()  {printf("blah
");}
   int i;
};

void main(int, char**)
{
   ((foo*)NULL)->blah();
}

Ever crash, or do anything other than output blah, on any compiler you are aware of? Will any function crash, when called via a NULL pointer, if it doesn't access any members (including the vtable)?

There have been other questions on this topic, for instance Accessing class members on a NULL pointer and Is it legal/well-defined C++ to call a non-static method that doesn't access members through a null pointer?, and it is always pointed out that this results in undefined behavior. But is this undefined in the real world, or only in the standard's world? Does any extant compiler not behave as expected? Can you think of any plausible reason why any future compiler wouldn't behave as expected?

What if the function does modify members, but the NULL ptr is guarded against. For instance,

void foo::blah()
{
   foo* pThis = this ? this : new foo();
   pThis->i++;
}

Edit: For the record, the reason I wanted this was to make the interface to my linked list class as easy and concise as possible. I wanted to initialize the list to NULL have idiomatic usage look like:

pList = pList->Insert(elt);
pList = pList->Remove(elt);
...

Where all the operators return the new head element. Somehow I didn't realize that using a container class would make things even easier, with no downside.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can you think of any plausible reason why any future compiler wouldn't behave as expected?

A helpful compiler might add code to access the real object under the hood in debug builds in the hope of helping you catch this issue in your code early in the development cycle.

What if the function does modify members, but the NULL ptr is guarded against. For instance,

void foo::blah()
{
   foo* pThis = this ? this : new foo();
   pThis->i++;
}

Since it is undefined behavior to call that function with a null pointer, the compiler can assume that the test will always pass and optimize that function to:

void foo::blah()
{
   this->i++;
}

Note that this is correct, since if this is not null, it behaves as-if the original code was executed, and if this was null, it would be undefined behavior and the compiler does not need to provide any particular behavior at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...