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!
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 :-)
After calling exit
you're beyond malloc
and friends but the OS reclaims everything. Think of malloc
as a convenient intermediary between the OS and your process.
Just a note that at those 2 calls to exit you have - you have failed to allocate any memory, so freeing that pointer is going to be pretty pointless (and might crash, depending on how old your C runtime system is).
So, no, you shouldn't free it, because it doesn't exist.
I'd have said in the case of a fatal error like that, you probably don't want to bother freeing up memory.
However, if your program exits normally, yes, you should try and free up all the memory you have allocated. That can be quite tricky sometimes.
When you exit the program, all allocated memory is reclaimed by the OS (both the stack and the heap). Your program doesn't leave any footprint in the RAM, unless you work outside the program's memory through buffer overflows and such.