What happens if I don't 'delete'?

c++, memory-management

Solution

It all depends on what your program does, and how much memory it uses - at any given time and overall throughout its runtime.

Say for example you write a mail server, that allocates memory to hold each email it receives. But it doesn't actually need to store every email that goes through it. So after a few days of receiving and forwarding emails, the mail server can't allocate any more memory, it has consumed every available byte of memory - but it's not actually doing anything useful with that memory, since the emails are no longer in use - they have been dealt with.

On the other hand, if we write our mail server program that allocates, say, 1 MB of buffer to read in an email, process it, and when it's done with, the memory is reused for another email, then there's little point in freeing that memory, ever.

And if we write a program that just reads a file, loading the entire file into memory, and when it has counted all the letters for statistical purposes, prints the stats and exits, whether that allocates a lot of memory or not doesn't really matter.

Of course, all this assumes that the call to `new` is SIMPLY to allocate memory. If the constructor of the object does something more complex, like open a file, acquire a lock or something else, then all sorts of bad things could happen pretty soon if the destructor isn't called.

The OS will (for the commonly used OS's such as Linux, macOS, iOS, other Unix-systems, Windows, DOS, OS/2, etc) free the memory used by your application.

Problem

What happens if I allocate some memory during execution but never call `delete` and the program terminates? Will the OS free all memory I allocated and no memory will be 'wasted'? Or will I lose a portion of memory until the computer is restarted? Obviously I know good coding practice is to make sure you delete what you don't need, so I'm not just asking "what is the point of `delete`"; I'm simply interested to know what happens inside my RAM.

Original source

Related problems