After application exits, all memory allocated on the heap is returned to the operating system (*) (in most cases, although I didn't hear about OS, that doesn't do it (**)). So, is it a memory leak? It depends.
In such simple case, there is no harm, but consider following situation:
class C
{
protected:
//file handles, network connections, database handles
public:
C()
{
//initialize resources
}
~C()
{
//release resources
}
};
static C* globals = new C[10];
In terms of C++, calling new
/new[]
is directly connected to initialization using constructor, while delete
/delete[]
also means calling the destructor of a particular class. So in this case resources owned by C
will never be released - yes, memory occupied by globals
will be freed, but their destructors will never be called. It may or may not be harmful, but remember, that:
- if you have written data to file and didn't close it, data may not get flushed
- if you didn't close temporary file, it may not get removed
- network connections should be always closed gracefully, when possible
- databases connections should also be explicitly closed
The point is, that memory is not always the most important part. Sometimes, not releasing more complex resources can have serious consequences, that can lead to undefined behaviour of your program.
(*) How is this possible? Most modern operating system have a different variations of "Memory Manager". Userland processes only see so-called virtual memory, which is not directly related to physical memory in a way, that you probably could expect - it essentially maps virtual addresses, into physical addresses in computer memory. After program terminates, its whole virtual space is released and all addresses, that were mapped by it, become available to other processes.
(**) As far as I know, DOS, Windows 3.x and probably MacOS 9 and earlier may not properly reclaim all memory allocated by processes after they terminate. But these are definitely not used anymore.