This question already has an answer here:
Is it really important to free allocated memory if the program's just about to exit?
Generally, the OS will reclaim the memory, so no, you don't have to
free() it. But it is really good practice to do it, and in some cases it may actually make a difference. Couple of examples:
- You execute your program as a subprocess of another process. Depending on how that is done (see comments below), the memory won't be freed until the parent finishes. If the parent never finishes, that's a permanent leak.
- You change your program to do something else. Now you need to hunt down every exit path and free everything, and you'll likely forget some.
- Reclaiming the memory is of OS' volition. All major ones do it, but if you port your program to another system it may not.
- Static analysis and debug tools work better with correct code.
- If the memory is shared between processes, it may only be freed after all processes terminate, or possibly not even then.
By the way, this is just about memory. Freeing other resources, such as closing a file (
fclose()) is much more important, as some OSes (Windows) don't properly flush the stream.