Should I free memory before exit?

前端 未结 5 1024
闹比i
闹比i 2020-11-28 11:49

Should I free all my mallocated memory when I am exiting program in the due of error?

something = (char**) malloc (x * sizeof(char*));
for (i = 0; i < x;          


        
5条回答
  •  野性不改
    2020-11-28 12:36

    This is actually a really hard, imponderable question.

    Pro (in favor of freeing everything before exit):

    • no bugs or memory leaks later if code is rearranged
    • no false positives from valgrind or memory leak checker
    • no memory leaks if you're running under a buggy OS, or no OS at all

    Con (just exit, don't worry about freeing everything):

    • freeing everything can be a lot of work
    • freeing everything can introduce bugs and crashes
    • your OS really, really ought to reclaim all resources for you when you exit

    And, one more point (not sure if it's a pro or a con): on the majority of systems, calling free does not return memory to the Operating System (only exiting does that).

    In the end, you will have to decide which of these pros and cons matters most for you. Different programmers on different projects under different circumstances will reach different conclusions; there is no one-size-fits-all answer here.

    See also this previous Stack Overflow question. See also question 7.24 in the C FAQ list.

提交回复
热议问题