Additional to the answers already given, note that the mention of freeing
"in a function" ensures that your program doesn't develop what is known as
a memory "leak". This occurs when you allocate memory for an object
repeatedly without ever freeing the allocations.
If you write a function that does a malloc every time it is called, but
don't free the allocation before exiting that function, then the next time
that same function is called it will malloc again and assign the return to
the same pointer as the first time. That will cause you to lose the
reference to the earlier allocation and that allocation will persist
until your program exits. Thus your program will use more and more memory
the longer it executes and keeps repeating calls to the function.
Failing to free a buffer when it is no longer needed means that the memory
allocated is not made available for reuse by your program. With today's
systems where gigabytes of memory is often available for each process the
loss may not be noticeable. But on systems with limited memory available
for each process (e.g. - embedded systems, DOS, etc.) a program may find
that an attempt to allocate memory fails because not enough is left
available. Freeing larger allocations such as for file buffers, large
arrays, etc. helps to avoid this condition.
The above alludes to programming in C in an environment that doesn't
provide for automatic "garbage collection". In C++ one can use "smart
pointers" which will automatically release memory from allocations
(new/new[]) when the pointer goes out of scope. Then there are also
allocations done when using a framework such as .NET which will do
automatic "garbage collection". But for programming in straight C
"best practice" is to cultivate the habit of freeing allocations
when they are no longer needed.
As noted by others, when a program ends under Windows the operating system
will reclaim any memory that was allocated and never released. That wasn't
always the case, and allocated memory would be lost for reuse by new
program executions until the operating system was rebooted.
- Wayne