Question:
If I use malloc locally in a function do I have to use free as well? Won’t someother piece of the application eventually chew up the memory I mallocd, so it doesn’t matter what happens to it when I’m done with it inmy function?
Answer:
Your code must include a matching free() call for every malloc’d pointer. Otherwise, your code will cause memory leaks.
There is no magic sorcerer in the application that will automatically reclaim the allocated memory because both C and C++ assume that if you don’t explicitly free dynamically-allocated memory, you want it to remain available throughout the lifetime of the application.
Depending on the operating system your using, the allocated memory may or may not be reclaimed after the application terminates, but never during the application’s execution. For example, in DOS, leaked memory is lost until you reboot. On Win32, the leaked memory will be reclaimed after the application has terminated.