The following code has an obvious memory leak:
void Memory_Leak(void);
void Lots_Of_Other_Stuff(void);
int main(){
Memory_Leak();
Lots_Of_Other_Stuff();
}
void Memory_Leak(void)
{
int *data = new int;
*data = 15;
return;
}
void Lots_Of_Other_Stuff(void){
//allocates/deletes more memory
//calls functions
//etc..
return;
}
For the duration of the program, can the memory ever be recovered?
Can the program write over lost memory, and reach a state where no memory has been lost?
Can the Operating System recover it while the program is still running?
Standard C++ does not have any way to know you’re not using the memory anymore.
Some platform-specific mechanisms exist for introspecting the memory heap, usually for debugging, e.g.
http://msdn.microsoft.com/en-us/library/974tc9t1(v=vs.80).aspx
In theory, you could maybe use something like that to take a “snapshot” of the heap state before you ran your
Memory_Leak(). Then after it was finished you could look for anything you considered to be a leak and free it. But don’t do it. Only mentioning it for thoroughness.The C++ way of avoiding leaks is to use “smart” pointers instead of “raw/naked/dumb/C-style” pointers. For instance:
The shared pointer is an object with a destructor, so it has an opportunity to run some code when its lifetime is over. That code releases the memory. In this case, the local variable
dataends its life at the return statement, and if that shared_ptr hasn’t been copied and stored elsewhere then the reference count held on the memory for the integer will be zero. So that memory will be freed.You can read up more on smart pointers here on StackOverflow, Wikipedia, Google, etc.
http://en.wikipedia.org/wiki/Smart_pointer