In either C or C++, should I check pointer parameters against NULL/nullptr?

后端 未结 20 2079
有刺的猬
有刺的猬 2020-11-27 03:54

This question was inspired by this answer.

I\'ve always been of the philosophy that the callee is never responsible when the caller does something stupid, like passi

相关标签:
20条回答
  • 2020-11-27 04:31

    I am pro defensive programming.

    Unless you can profile that these nullptr checkings happen in a bottleneck of your application... (in such cases it is conceivable one should not do those pointers value tests at those points)

    but all in all comparing an int with 0 is really cheap an operation. I think it is a shame to let potential crash bugs instead of consuming so little CPU.

    so: Test your pointers against NULL!

    0 讨论(0)
  • 2020-11-27 04:31

    I don't think it's the responsibility of the callee to deal with such things

    If it doesn't take this responsibility it might create bad results, like dereferencing NULL pointers. Problem is that it always implicitly takes this responsibility. That's why i prefer graceful handling.

    0 讨论(0)
  • 2020-11-27 04:31

    Yes, you should check for null pointers. You don't want to crash an application because the developer messed something up.

    0 讨论(0)
  • 2020-11-27 04:32

    One thing you have to consider is what happens if some caller DOES misuse your API. In the case of passing NULL pointers, the result is an obvious crash, so it's OK not to check. Any misuse will be readily apparent to the calling code's developer.

    The infamous glibc debacle is another thing entirely. The misuse resulted in actually useful behavior for the caller, and the API stayed that way for decades. Then they changed it.

    In this case, the API developers' should have checked values with an assert or some similar mechanism. But you can't go back in time to correct an error. The wailing and gnashing of teeth were inevitable. Read all about it here.

    0 讨论(0)
  • 2020-11-27 04:36

    While in general I don't see the value in detecting NULL (why NULL and not some other invalid address?) for a public API I'd probably still do it simply because many C and C++ programmers expect such behavior.

    0 讨论(0)
  • 2020-11-27 04:36

    In C++, if you don't want to accept NULL pointers, then don't take the chance: accept a reference instead.

    0 讨论(0)
提交回复
热议问题