My program (a text-mode web browser) is dynamically allocating memory.
I do free unneeded blocks during runtime, of course. And I do free everything before normal termination - so that memory leak checkers won't give me false positives (and to be flexible should major refactorings ever become needed).
Now, what I do not do is freeing memory before abnormal termination. (Currently, my program terminates on signals and after failed mallocs/reallocs.)
My question is: Do you consider this bad style? Should I free on abnormal termination?
Before freeing a pointer, the programmer should make sure that the pointer was previously allocated on the heap and that the memory belongs to the programmer. Freeing an unallocated pointer will cause undefined behavior in the program.
Most memory on most OSes however will be automatically reclaimed when the process exits.
Sometimes there just isn't enough memory, meaning that malloc isn't guaranteed to return a pointer to usable memory. If it isn't able to allocate memory, it will return a null pointer, NULL .
However on long running programs, failing to free memory means you will be consuming a finite resource without replenishing it. Eventually it will run out and your program will rudely crash. This is why you must free memory.
No. I think it's perfectly acceptable to simply throw up your hands and let the OS reclaim the memory after the program terminates. I think if this is truly an abnormal situation and the intention is to have the program terminate, then a well-behaved program should simply clean up any disk resources/locks, and exit as quickly as possible.
In my opinion freeing the memory on crash isn't necessary. When your process terminates, OS will reclaim the memory, so all you have to do is exit.
On the other hand, other resources (e.g. open files) should be closed or at least flushed -- if not, they may not be stored/stored incomplete because of the buffering.
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