Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Beginner
Jan 19, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Malloc and Free

If I use malloc locally in a function do I have to use free as well? Won't some other 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 in my function?

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.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date