devxlogo

Malloc and Free

Malloc and Free

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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist