Title: Will leaked memory always remain lost for the duration of C/C++ program?
Tags: c++;c;memory;memory-management;operating-system
Question: 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?

Comment: It depends on the OS, short answers, I'm pretty sure it's: no, no, no

Here is the accepted answer: 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:

```void Memory_Leak(void) // actually, with this change it won't leak anymore...
{
    shared_ptr<int&gt; data (new int);
    *data = 15;
    return;
}
```

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 ```data``` ends 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

Comment for this answer: @lori For the literal code exactly as written, yes.  But the nuances of the `unique_ptr` and `st181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16move` etc. are rather deep for someone new to the C++ memory model, who might intend to pass it as a parameter or put the pointer into a standard container.  Seemed a bit less cruel to start with `shared_ptr` in this case.  :-)
Comment for this answer: In this instance I'd suggest a `unique_ptr` rather than `shared_ptr`, considering the reference counting overhead that comes with `shared_ptr`

Here is another answer: No, the memory will not be recovered until your program finishes executing.

No. If you are able to write over that memory then there was never a memory leak in the first place since you must still have some pointer to the allocated memory (allocating new memory with new or malloc will never give you the same already allocated memory).

No. The OS has no way to know that your program is not still using that memory, so no it cannot recover it. 


Here is another answer: ```
  For the duration of the program, will the memory every be recovered?
```

No: unless you magically guess the address of the lost variable and call ```delete```, it is gone.

```
  Can the program write over this memory now, and reach a state where no memory has been lost?
```

No - again, once you've lost the reference to the address of the allocated memory region, you cannot recover the corresponding memory chunk.

```
  Can the Operating System recover it while the program is still running?
```

No, the operating system does not recover that memory until the process exits.


Here is another answer: Yes, the memory is lost for the duration of the program. There is no way for the operating system to know that you have lost all references to this memory location.

This is one of the fundamental differences between C/C++ and Java/C#.

Garbage collection is the mechanism which is used to work out whether a memory location no longer has anything referencing it, and is what allows the OS to reclaim unused memory - and is not available in C/C++

Comment for this answer: Well, wouldn't you tell a C programmer *"C++ uses iostream instead of printf"*, even if the functions still exist? To most C++ zealots here, *"Modern C++"* equates with *"idiomatic C++"* and *"C++11"* equates with *"standard C++"*. In practical terms many people cannot (or simply have not) made that leap...but someone has to be pushing the cultural shift or it'll never happen. Bjarne wrote in one of his recent books *"Unless your name is Stroustrup, this is not your father's C++."*...and it seems to be his opinion that naked pointers are no longer a legitimate option for serious projects.
Comment for this answer: C++ uses smart pointers for fine grained deterministic garbage collection. Its optional to use so its not all the way over with Java/C# but its not on the same side as C either.
Comment for this answer: C++ that uses raw pointers (ie manual memory management) is what we refer to as "C with classes". Modern C++ uses smart pointers. So you could add another language to your little list.  `C/"C with classes" -> C++ -> Java/C#`
Comment for this answer: I agree with most of what you've said there, but since C++ doesn't use smart pointers by default, I would reword that to `there is an **option** to use smart pointers in C++` rather than `C++ **uses** smart pointers`
Comment for this answer: @HostileFork - I'll buy that! :)

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 4, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2012:00:11/27/12', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c++><c><memory><memory-management><operating-system>', 'Title': 'Will leaked memory always remain lost for the duration of C/C++ program?', 'ViewCount': 437, 'id': 13576969, 'user_AboutMe': '<p>and programming</p>\n', 'user_AccountId': 809083.0, 'user_DisplayName': 'Trevor Hickey', 'user_Reputation': 34762.0, 'user_Views': 3906.0, 'user_id': 908939.0}}