While doing programming i am using assert as well as NULL pointer validation.
But as i know assert will be useful only in DEBUG mode.
My question is suppose i have a internal pointer which i am sure cant be NULL example function returning a pointer(but the pointer is not a member of class) in such cases i can use assert
test* ptr = fun(); // return a pointer of type test
assert(ptr);
//do some operation
or NULL pointer validation
test* ptr = fun(); // return a pointer of type test
assert(ptr);
if (NULL != ptr)
{
//do some operation
}
Here which code practice is good.As per my understating it will be second one. Because i have faced some situations where the value of ptr returns NULL due to some abnormal cases that we cant even think of.
But do we have any other better options?
assert
says "if this isn't true, there is a logic error in my code". If you are putting in code to handle the fact that pointer might be null then it is the assert call which is redundant. You should add logging and handling to the 'else' case instead. This way your debug build will run in the same way as your release build, even in the null pointer case.
If you really mean assert and you have to abort on a null pointer then enable asserts in your release build or use an alternative release-enabled assert mechanism.
The only reason for a debug-only assert is a check for a logic error that is too expensive to make in release code. Normally a null check for a pointer won't fit into this category.
The real solution depends on the semantic of the function fun
.
If returning NULL
is semantically invalid, then I think fun
should throw an appropriate exception (such as std::logic_error
1) instead of returning NULL
, and you could use assert
on the call site to ensure that fun
is working fine, and if it is not working fine, then abort the program. In this way, the bug in fun
doesn't propagate to the rest of the program, as it is caught immediately.
However, if returning NULL
from fun
is semantically valid, then you should check the return value on the call-site using if
and assert
is not really needed in this case, because you will use if
anyway.
1. Or you could use std::runtime_error
or std::domain_error
.
I recommend you to use your own code for assertion. as you said, assert only works in debug mode.
So, if it is working in release mode, it doesn't work.
if you use your own assertion code. you can simply find out what it is wrong.
test* ptr = fun(); // return a pointer of type test
MyOwnAssert(ptr);
void MyOwnAssert(void* pPointer)
{
if (NULL == pPointer)
abort();
}
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