1

Been reading C++ books but I can't seem to find the answer. All I know is dynamic memory allocation such as when I make a function:

void memoryleak(){ int * ptr = new int; } 

It allocates a memory and returns that memory to the pointer, however, since the pointer is a local variable, after the memoryleak(), the pointer which contains the reference of the memory was deallocated because it's static, hence the allocated memory is lost and cannot be reused for the program.

But does it mean the memory is lost forever or only until the program is terminated like after compiling this code snippet:

main(){ int * ptr = new int; } 

After the program terminates, will the memory stay allocated or deallocated? If it stays allocated, does restarting the PC make the PC deallocate all used memory? Another question, out of curiosity, about the memory which they use (in allocation), is it RAM? :)

1
  • 1
    Please pick your favourite answer and accept it. Do likewise for your other questions. See the faq Commented May 19, 2012 at 12:09

4 Answers 4

4

The answer depends on who you ask. As far as the C++ language goes, the memory is just lost. There's no way to get it back.

But any reasonable OS is smart enough to know what memory has been allocated to which process, and when a process terminates, it reclaims all that memory.

So in practice, the answer is that the memory is only leaked as long as the process lives. After that, the OS scoops it all up, and is ready to reuse it elsewhere.

Of course, this is how common mainstream OS'es like Windows, Linux or OSX behave. A sufficiently primitive OS might not do this.

Sign up to request clarification or add additional context in comments.

1 Comment

Primitive OS: Like those used an embedded device.
4

After the process terminates all the resource is reclaimed. This includes address space , scheduling primitives etc.

Comments

2

When the program terminates, the OS will re-claim all memory that the process allocated. Any memory that you leak during your program's life will be returned to the pool of available memory once your program terminates.

When you allocate memory with new then this will be backed by RAM. If you allocate more memory than is available, then the computer may use a swap file on your disk instead.

Comments

1

All memory claimed by the program is released to the OS when the program terminates, so no, the memory is not lost. When your program finishes, the memory will be available for others.

Another question, out of curiosity, about the memory which they use (in allocation), is it RAM?

Yes, the memory is RAM.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.