I stumbled upon this piece of code which seems totaly broken to me, but it does happen that this
is null
. I just don't get how this can be null
it is inside a normal method call such as
myObject->func();
inside MyObject::func()
we have
if (!this) { return false; }
is there any way I can have the first line to throw a NullPointerException
instead of going inside the null
(?) method?
If you have:
MyObject *o = NULL;
o->func();
What happens next depends on whether func
is virtual. If it is, then it will crash, because it needs an object to get the vtable from. But if it's not virtual the call proceeds with the this pointer set to NULL.
I believe the standard says this is "undefined behaviour", so anything could happen, but typical compilers just generate the code to not check whether the pointer is NULL. Some well known libraries rely on the behaviour I described: MFC has a function called something like SafeGetHandle
that can be called on a null pointer, and returns NULL in that case.
You might want to write a reusable helper function:
void CheckNotNull(void *p)
{
if (p == NULL)
throw NullPointerException();
}
You can then use that at the start of a function to check all its arguments, including this
:
CheckNotNull(this);
A way to trap these kind of errors (by design) is using a pointer-wrapper class (resembling a shared_ptr
) that throws upon creation with a null pointer argument. It may throw also when dereferenced, but that's a little late - better than nothing, I guess.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With