Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I free allocated memory on abnormal termination?

Tags:

c

malloc

free

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?

like image 697
RWS Avatar asked Jul 23 '10 10:07

RWS


People also ask

What happens if you free unallocated memory?

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.

Is memory automatically freed when a program exits?

Most memory on most OSes however will be automatically reclaimed when the process exits.

What happens if you dont malloc?

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 .

Why do you have to free memory in C?

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.


2 Answers

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.

like image 91
Gian Avatar answered Sep 23 '22 06:09

Gian


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.

like image 26
Archie Avatar answered Sep 23 '22 06:09

Archie