Search code examples
cmemory-managementmallocfreeautomatic-storage

Do we really have to free() when we malloc()? What makes it different from an automatic variable then?


The OS will just recover it (after the program exits) right? So what's the use other than good programming style? Or is there something I'm misunderstanding? What makes it different from "automatic" allocation since both can be changed during run time, and both end after program execution?


Solution

  • When your application is working with vast amounts of data, you must free in order to conserve heap space. If you don't, several bad things can happen:

    • the OS will stop allocating memory for you (crashing)
    • the OS will start swapping your data to disk (thrashing)
    • other applications will have less space to put their data

    The fact that the OS collects all the space you allocate when the application exits does not mean you should rely upon this to write a solid application. This would be like trying to rely on the compiler to optimize poor programming. Memory management is crucial for good performance, scalability, and reliability.

    As others have mentioned, malloc allocates space in the heap, while auto variables are created on the stack. There are uses for both, but they are indeed very different. Heap space must be allocated and managed by the OS and can store data dynamically and of different sizes.