Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is freeing allocated memory needed when exiting a program in C

Tags:

If I allocated memory in my C program using malloc and now I want to exit, do I have to free the allocated memory, or can I assume that since my entire program terminates, it will be freed by the OS?

I run in Linux environment.

like image 227
SIMEL Avatar asked Apr 10 '11 13:04

SIMEL


People also ask

Do you have to free memory at the end of a program?

It is not mandatory, but it can have benefits (as well as some drawbacks). If the program allocates memory once during its execution time, and would otherwise never release it until the process ends, it may be a sensible approach not to release the memory manually and rely on the OS.

What happens to the allocated memory after a program exits?

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.

What happens if you don't free memory in C?

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).

What does freeing memory do in C?

It means that whenever you declare a regular variable of any data type in C, the programming language itself is responsible for deallocating or releasing this memory once your program has been executed successfully.


2 Answers

Any modern operating system will clean up everything after a process terminates, but it's generally not a good practice to rely on this.

It depends on the program you are writing. If it's just a command line tool that runs and terminates quickly, you may not bother cleaning up. But be aware that it is this mindset that causes memory leaks in daemons and long-running programs.

like image 126
Blagovest Buyukliev Avatar answered Oct 21 '22 05:10

Blagovest Buyukliev


It can be a good design and very efficient to simply exit and allow the operating system to clean everything up. Apple OS X now does this by default: applications are killed without notice unless the application sets a "don't kill me" flag.

Often, freeing every memory allocation takes significant time. Some memory pages may have been swapped out and must be read back in so they can be marked as free. The memory allocator has to do a lot of work updating free memory tracking data. All of this effort is a waste because the program is exiting.

But this must be done by design and not because the programmer has lost track of allocated memory!

like image 33
Zan Lynx Avatar answered Oct 21 '22 03:10

Zan Lynx