Checking for null before pointer usage

后端 未结 13 2573
孤独总比滥情好
孤独总比滥情好 2021-02-20 09:32

Most people use pointers like this...

if ( p != NULL ) {
  DoWhateverWithP();
}

However, if the pointer is null for whatever reason, the functi

13条回答
  •  臣服心动
    2021-02-20 09:47

    When it's acceptable for the program to just crash if a NULL pointer comes up, I'm partial to:

    assert(p);
    DoWhateverWithP();
    

    This will only check the pointer in debug builds since defining NDEBUG usually #undefs assert() at the preprocessor level. It documents your assumption and assists with debugging but has zero performance impact on the released binary (though, to be fair, checking for a NULL pointer should have effectively zero impact on performance in the vast majority of circumstances).

    As a side benefit, this is legal for C as well as C++ and, in the latter case, doesn't require exceptions to be enabled in your compiler/runtime.

    Concerning your second question, I prefer to put the assertions at the beginning of the subroutine. Again, the beauty of assert() is the fact that there's really no 'overhead' to speak of. As such, there's nothing to weigh against the benefits of only requiring one assertion in the subroutine definition.

    Of course, the caveat is that you never want to assert an expression with side-effects:

    assert(p = malloc(1)); // NEVER DO THIS!
    DoSomethingWithP();    // If NDEBUG was defined, malloc() was never called!
    

提交回复
热议问题