C++ – How far can memory leaks go

cmemorymemory-leaks

I've run into memory leaks many times. Usually when I'm malloc-ing like there's no tomorrow, or dangling FILE *s like dirty laundry. I generally assume (read: hope desperately) that all memory is cleaned up at least when the program terminates. Are there any situations where leaked memory won't be collected when the program terminates, or crashes?

If the answer varies widely from language-to-language, then let's focus on C(++).

Please note hyperbolic usage of the phrase, 'like there's no tomorrow', and 'dangling … like dirty laundry'. Unsafe* malloc*ing can hurt the ones you love. Also, please use caution with dirty laundry.

Best Answer

No. Operating systems free all resources held by processes when they exit.

This applies to all resources the operating system maintains: memory, open files, network connections, window handles...

That said, if the program is running on an embedded system without an operating system, or with a very simple or buggy operating system, the memory might be unusable until a reboot. But if you were in that situation you probably wouldn't be asking this question.

The operating system may take a long time to free certain resources. For example the TCP port that a network server uses to accept connections may take minutes to become free, even if properly closed by the program. A networked program may also hold remote resources such as database objects. The remote system should free those resources when the network connection is lost, but it may take even longer than the local operating system.