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!
The memory is reclaimed by the Operating system once your program exits. The OS doesn't understand that your program leaked memory, it simply allocates memory to the program for running and once the program exits it reclaims that memory.
You have to free() the allocated memory in exact reverse order of how it was allocated using malloc() . Note that You should free the memory only after you are done with your usage of the allocated pointers.
If free() is not used in a program the memory allocated using malloc() will be de-allocated after completion of the execution of the program (included program execution time is relatively small and the program ends normally).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With