checking for NULL before calling free

前端 未结 8 659
终归单人心
终归单人心 2020-12-03 13:45

Many C code freeing pointers calls:

if (p)
  free(p);

But why? I thought C standard say the free function doesn\'t do anything

8条回答
  •  臣服心动
    2020-12-03 14:03

    Compilers, even when inlining are not smart enough to know the function will return immediately. Pushing parameters etc on stack and setting the call up up is obviously more expensive than testing a pointer. I think it is always good practice to avoid execution of anything, even when that anything is a no-op. Testing for null is a good practice. An even better practice is to ensure your code does not reach this state and therefore eliminate the need for the test altogether.

提交回复
热议问题