Checking for null before pointer usage

后端 未结 13 2653
孤独总比滥情好
孤独总比滥情好 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

    Could it possibly be more beneficial to just not check for NULL?

    I wouldn't do it, I favor assertions on the frontline and some form of recovery in the body past that. What would assertions not provide to you, that not checking for null would? Similar effect, with easier interpretation and a formal acknowledgement.

    In relation to the first question, do you always check for NULL before you use pointers?

    It really depends on the code and the time available, but I am irritatingly good at it; a good chunk of 'implementation' in my programs consists of what a program should not do, rather than the usual 'what it should do'.

    Secondly, consider you have a function that takes a pointer as an argument...

    I test it in the function, as the function is (hopefully) the program that is reused more frequently. I also tend to test it before making the call, without that test, the error loses localization (useful for reporting and isolation).

提交回复
热议问题