0

If I continuously allocate memory using malloc without freeing them, what happens to the memory after the program is exited? Does the OS free it or is it still under allocattion?

pbsh
  • 143
  • 7
  • It depends on the operating system. Some free it, others don't. Always explicitly freeing what you allocate (and that goes for *all* resources, not only memory) is generally a good idea no matter what, even if the OS free all resources on process exit. – Some programmer dude Oct 31 '16 at 07:40
  • All malloc does is making a larger and larger part of the virtual memory range part of the process' address space. The actual mapping doesn't happen until you access the memory, and those mappings are deleted when the process terminates – Einheri Oct 31 '16 at 07:41

1 Answers1

0

Usually yes. Long story shortened yes, it's freed.

When you create a new process, the OS is allocating a memory block for that specific process. In that memory block you're allocating almost how you want the memory (functions, signatures, variables, etc). These things translates into the following diagram:

Linux memory map with or without shared libraries

When the process terminates, the whole block of memory is recycled. It may take time while it's recycled and if there's a very fast succession of another process starting, another block will be used. If not this one would be used.

Said Hasanein
  • 320
  • 1
  • 5
  • 1
    That is the case in good operating systems, but not all operating systems throughout history have been good. I remember my friend complaining that under AmigaDos, memory that wasn't freed by an application wouldn't get freed at all. – supercat Apr 24 '18 at 18:47