Makes output () of free allocated memory on both _SUCCESS and _FAILURE

This is a short piece of code with two calls to exit(3) in the event of a failure. Do these calls free the memory allocated by malloc? A Google search once says what it does, and even more times, it doesn't ...

Should I add free ()?

Also: what is better if (!word) (it will also work, for example, for the word == 0, which is different from the word == NULL, so I assume this 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!

+7
source share
4 answers

Yes, all memory is back. BTW, what would you like to do with the remaining memory after exiting anyway?
Or are you worried about memory leak in exit() ? If the memory had not been recovered, this would have leaked a little more with each outgoing process, which no credible OS could allow. Therefore, with the exception of the OS buggy, stop worrying about memory and use exit() where you need it.

In order to answer the questions in the comments of your code, whether for free, I would say that the correct software development is to write the corresponding free with each malloc . If this is complicated, this indicates a structural problem in your code. The advantage of freeing up 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 the false positives from malloc that you showed us.

Note that after a failed malloc, it makes no sense to try to free the result - in any case, this is a null pointer.

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

+8
source

After calling exit you are outside malloc and friends, but the OS restores everything. Think of malloc as a convenient intermediary between the OS and your process.

+7
source

Just note that with these two calls to exit, you have failed to allocate any memory, so freeing this pointer will be pretty pointless (and it may fail, depending on how old your C runtime system is).

So no, you should not release it, because it does not exist.

I would say that in the event of such a fatal error, you probably would not want to free up memory.

However, if your program exits normally, yes, you should try to free up all the allocated memory. Sometimes it can be quite difficult.

+2
source

When you exit the program, all the allocated memory is restored by the OS (both the stack and the heap). Your program leaves no traces in RAM if you do not work outside the program memory through buffer overflows, etc.

+1
source

All Articles