In a C program, if I try to use malloc
and for some reason the pointer is NULL, I will terminate the program with exit(1);
as without that block of memory the program is essentially unusable. Upon using exit(1);
should I be releasing all of the memory I had allocated during the program or does that happen automatically?
Asked
Active
Viewed 82 times
1

ishaangupte
- 248
- 2
- 11
-
2Its better to free it up to avoid memory leaks. – Marko Taht Jul 08 '22 at 12:01
-
1If malloc returns a null, one may suspect heap corruption, so a clean release does not seem relevant. (But another possibility is that you are claiming too much memory.) – Jul 08 '22 at 12:04
-
So does this apply to mapped memory too or do I explicitly need to call `munmap`? – ishaangupte Jul 08 '22 at 12:09
-
1As @SupportUkraine calling `exit()` is usually for emergency termination. – Weather Vane Jul 08 '22 at 12:12
-
1@MarkoTaht: There cannot be any memory leak when exiting from a user program in a general purpose operating system, because the operating system reclaims all the resources of the program. – Eric Postpischil Jul 08 '22 at 12:21
-
1@EricPostpischil While in most cases it is true. And in general it is not a problem. But to account for those rare situations where something can go wrong it is better to free it up. Even OS can fail in the automated cleanup. Its more like added security. – Marko Taht Jul 08 '22 at 12:49
-
2@MarkoTaht if the program needs an unexpected exit it usually best to do the *minimum necessary* to inform and clean up. Something has gone wrong, and if you then try to handle all subsequent errors "cleanly" you can end up down a rabbit hole. I agree though, that in a typical return from `main()` it's good practice to clean up. If you can't easily do that, it perhaps shows a poorly organised data structure. – Weather Vane Jul 08 '22 at 13:00
-
After `exit()` process is terminated and all it's address space is freed. – dimich Jul 08 '22 at 13:09
-
3@MarkoTaht: If there is an OS bug reclaiming memory, calling `free` is not expected to help. `free` updates records internal to the process. – Eric Postpischil Jul 08 '22 at 13:16
-
@EricPostpischil I mean. during the exit() stuff can go wrong. So if you freed everything before exit, you are still good. But these situations are maybe 0.01% af all runs. Still a good practice is to clean up after yourself. – Marko Taht Jul 08 '22 at 14:41
-
1No, it is not good practice: https://stackoverflow.com/a/51636779/758133 – Martin James Jul 08 '22 at 23:02