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

Peter Cerba picture Peter Cerba · Aug 23, 2012 · Viewed 9.2k times · Source

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, and even more times, it doesn't...

Should I add free()?

Also: which is better if (!word)(it would also work for eg. word == 0 which is different from word == NULL, so I guess it is wrong) or if (word == NULL) ?

char *word = NULL, *temp = NULL;
    word = (char *)malloc(sizeof(char) * size);

    if (!word) {            /* or maybe rather it should be (word == NULL)  */
        perror("malloc fail");
        if (fclose(fp)) {
            perror("fclose fail");
            exit(3);                            /* exit without free ? */
        }
        exit(3);                                /* exit without free ? */
    }

Thanks in advance!

Answer

Jens picture Jens · Aug 23, 2012

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 :-)