Andrew said:
But you would need to have found a gigabyte of contiguous memory
dedicated to your program for this to be simple - otherwise you
would be in memory space also used by other applications, and
bookkeeping does matter.
Not necessarily. Most of the modern operating systems implement some
form of paging and virtual memory. Unused pages are simply paged out
to disk and mapped back to RAM only when accessed.
Under these types of systems, deallocating memory got from malloc
simply makes little or no difference to the memory management of the
OS. OTOH the standard library allocator can hand them out to future
requests, so it's usually a good idea to free() memory when you no
longer need it.
But from the OS's point of view, unused or stale pages are unmapped
from real addresses and written to disk, the space reclaimed can now
be mapped to other pages of other processes, or the current one. And
in systems like Linux, virtual memory allocations even greater than
available free physical memory are granted, with the system mapping
pages to physical RAM only on first use, or killing a random process
if it cannot.
I guess this is one reason why large programs like Firefox allocate
massive amounts of virtual memory when starting up, confident that a
majority of it will not actually reside in RAM. The concept of virtual
memory has made life easier for multitasking systems, but it does mean
that programs have gotten into the habit of allocating far more memory
than necessary, or in not deallocating when done.
Finally, when the process terminates, normally or abnormally, with or
without explicitly calling free() for each malloc(), all pages for the
process are simply reclaimed. Privileged processes can of course, play
with the system in ways normal processes can't.
But it's still a good idea to deallocate resources when you're
finished with them, unless doing so would not be worth it. And to know
it it'd be worth it, we need to know about other considerations. But
IMHO, manually deallocating memory before exit should be the rule
rather than the exception.