does exit() free allocated memory on both _SUCCESS and _FAILURE

前端 未结 4 2414
旧时难觅i
旧时难觅i 2021-02-19 16:43

This a short snippet of code, with two calls to exit(3) in case of failure. Do these calls deallocate memory allocated by malloc? Google search once says it does, a

4条回答
  •  盖世英雄少女心
    2021-02-19 17:22

    Yes, all memory is returned. BTW, what would you want to do with leftover memory after the exit anyway?
    Or are you worrying about a memory leak in exit()? If the memory weren't reclaimed, it would leak a bit more with each exiting process, which is something no credible OS could afford. So, except for a buggy OS, stop worrying about memory and use exit() wherever you need it.

    To answer the questions in the comments of your code, whether to free, I'd say it's proper software engineering to write a corresponding free with every malloc. If that appears hard, it is pointing to a structural problem in your code. The benefit of freeing all memory before exiting is that you can use powerful tools like valgrind to check for memory leaks in the rest of your code without false positives from the malloc you've shown us.

    Note that after a failed malloc there is no point in attempting to free the result--it's a null pointer anyway.

    And third, I prefer if (pointer == NULL) over if (!pointer) but this is totally subjective and I can read and understand both :-)

提交回复
热议问题