Should one really set pointers to `NULL` after freeing them?

前端 未结 10 1088
庸人自扰
庸人自扰 2020-11-28 03:27

There seem to be two arguments why one should set a pointer to NULL after freeing them.

Avoid crashing when double-freeing pointers.

Short

10条回答
  •  青春惊慌失措
    2020-11-28 04:04

    If you don't set the pointer to NULL there is a not-so-small chance, that your application continues to run in an undefined state and crashes later on at a completely unrelated point. Then you will spend a lot of time with debugging a nonexistent error before you find out, that it's a memory-corruption from earlier.

    I'd set the pointer to NULL because the chances are higher that you'll hit the correct spot of the error earlier than if you didn't set it to NULL. The logical error of freeing memory a second time is still to be thought of and the error that your application does NOT crash on null-pointer access with a large enough offset is in my opinion completely academic although not impossible.

    Conclusion: I'd go for setting the pointer to NULL.

提交回复
热议问题