Heap memory clearance when application closes abruptly - c++

As we know the heap is used for dynamic allocation of memory for an application. How is the heap memory cleared(and hence avoiding memory leaks) in case of abnormal application termination?
Consider the following scenarios:
Say an application crashes all of a sudden on Windows or Linux.
We force kill an application in linux: kill -9 <process_name>
A C++ program in Visual Studio throws an error in the middle of execution.
Is heap management and cleanup any different in the above cases? [Please add more use-case scenarios which might be of interest here]
This question came up in my mind since we always talk about ensuring no memory leak happens in our code. Now how do we handle scenarios where we force close an application which might result into a program exit without calling the memory free-up calls.
And if such memory leak happens repeatedly, is it possible that the OS becomes short of heap memory? Or does the OS have a way of handling it...

Assuming the OS is a typical implementation of Unix or Windows, the heap memory is released by the OS when the application is killed, no matter what method it is killed by.
Obviuously, other OS's may not do exactly this, and it's up to each OS to solve this problem in a meaningful way - I'm not aware of any OS that doesn't "clean up after killed processes", but I'm sure such a thing may exist in some corner of this world.
Edit: There may be OTHER resoources that aren't quite so easily released, such as shared memory or semaphores used by multiple. But most OS's tend to deal with those by releasing the reference of the application being killed, and letting other processes that wait for any "waitable object" (mutex, semaphore, etc) will be "let run".

"The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits" so killing/closing an application abnormally/normally won't leak any memory.

As for dynamic memory management you should use RAII(smart pointers is one example) to take care of memory leaks and management during exceptions and so on.
In cases where your application exits, the OS simply reclaims back all the memory it gave to the process. The OS doesn't understand leaks, it simply takes back what it gave to a process. So there is no leak per se. All memory is reclaimed. You might leak other resources(file descriptors etc) but a clever use of RAII should guard you against that.

It doesn't matter how your process closes, any remaining memory allocated from that process is freed by the OS memory manager when it closes. It's good practice for you to free all the memory you allocate before your process dies, but the available heap for the OS/other applications is the same after your process closes either way.

Related

c++ When does terminating program's memory leak matter?

I read wikipedia article saying
Memory leaks may not be serious or even detectable by normal means. In
modern operating systems, normal memory used by an application is
released when the application terminates. This means that a memory
leak in a program that only runs for a short time may not be noticed
and is rarely serious.
OS automatically release normal memory when terminating. Therefore, if memory leak was not serious by all means, leaked memory by program may not be matter after termination.
But it mentions only in case of "normal memory" and I got worried.
Could anyone explain what non-normal memory means?
How about few philosophical reasons?😀
For starters, if you ever need to redesign concept of lifetime in your program later, such as switch to a service, dll, multidoc support, or something like that, addressing this will become a must and an extra cost. Secondly, if the program does not free memory, chances are it does not release other critical resources, file locks on servers, for example (pure speculation, of course, I do not know what your program does).
But memory release on process termination will be guaranteed, outside of real-time systems on specialized hardware. Those can behave very differently.
In general; A program that leaks memory is only a problem while that program is running. It will take up more memory than it needs and may even run out. But, as soon as the program terminates, the OS kernel reclaims all memory that the program ever allocated, so it will all be free again and available for other uses.
It's actually a fairly common trick to intentionally leak memory on shutdown in some cases. If you know that your objects destructors don't do any work that is of any consequence if the program is shutting down anyway, then it can be faster to just leak the objects and let the OS clean up when you are terminating, rather than running all the destructors. However; only do that if you have a good reason to and really know what you are doing and why you are doing it.

memory leaks when program is closed with x

Might be a stupid question, but if I create a console-application that dynamicly creates object and such, I make sure to free the memmory at shutdown. What happens if a user closes the application with the "x" button on the window? will there be memoryleaks and if so, how do i prevent it?
No, there won't be any memory leaks.
When a user closes your application the process in which your appication runs gets terminated.Once a process gets terminated, the Operating System(OS) simply reclaims all the memory it had allocated to the process.
Note that for an OS there is no importance whether memory was leaked by the application or not it is simply reclaiming what it allocated to the process.
The application will simply be killed. In this case, memory leaks don't really happen since the OS do the cleanup for you.
Unless you have an embedded (or buggy) O/S you don't need to do anything.
If you do have an embedded (or buggy) O/S, you need to rigorously keep track of all your memory allocations and ensure there's a corresponding free. For a buggy O/S, you should additionally complain to the provider of said O/S

Return of memory at the termination of a C++ program

When a C++ program terminates, the RAM used during the run gets cleaned and is returned to the system, correct?
Question 1)
Is this memory returned managed by C++ language features or by the computer hardware itself?
Question 2)
Does the memory get returned efficiently/safely, if I terminate a run using ctrl+Z in Unix terminal?
When a C++ program terminates, the RAM used during the run gets cleaned and is returned to the system, correct?
Correct. By System, I hope you mean, Operating System.
Question 1) Is this memory returned managed by C++ language features or by the computer hardware itself?
The returned memory is managed by the operating system (if I correctly understand the question). And before returning to the OS, the memory is managed by the process; in low-level, which means, managed by various language features, such as allocation- deallocation mechanism, constructors, destructors, RAII, etc.
Question 2) Does the memory get returned efficiently/safely, if I terminate a run using ctrl+Z in Unix terminal?
Ctrl+Z suspends the process. It doesn't terminate it. So the memory doesn't get returned to the OS as long as the process is not terminated.
In linux, Ctrl+C terminates the process, then the memory returns to the OS.
Typically both. At least assuming normal termination, destructors will run, which will typically free the memory associated with those objects. Once your program exits, the OS will free all the memory that was owned by that process.
A forced termination often won't run the destructors and such, but any reasonable operating system is going to clean up after a process terminates, whether it did so cleanly or not. There are limits though, so if you've used things like lock files, it probably can't clean those up.
Q: When a C++ program terminates, the RAM used during the run gets
cleaned and is returned to the system, correct?
A: Correct. This is true for ANY program, regardless of the language it was written in, and regardless of whether it's Linux, Windows or another OS
Q Is this memory returned managed by C++ language features or by the
computer hardware itself?
A: Neither: the operating system is responsible for managing a process's memory.
Q: Does the memory get returned efficiently/safely, if I terminate a
run using ctrl+Z in Unix terminal?
A: OS resources (such as memory) are freed. But you can leave files corrupted, IPCs locked, and other Bad Things that are beyond the OS's control if you kill a program gracelessly.
'Hope that helps
Is this memory returned managed by C++ language features or by the computer hardware itself?
Both occur, assuming a proper shutdown (vs. a crash or kill). The standard C/C++ library deallocates any (non-leaked) memory it allocated via OS system calls and ultimately the OS cleans up any leaked memory.
Does the memory get returned efficiently/safely, if I terminate a run using ctrl+Z in Unix terminal?
Ctrl-Z suspends a process on Unix. If you terminate it using kill or kill -9, the memory will be reclaimed (safely / efficiently) by the OS.
They say that dynamically allocated memory is only returned by you, the programmer. For example, a
myclass *obj = new myclass();
always has to have a corresponding
delete obj;
somwehere, or else your program will leak memory, meaning the operating system could think that certain parts of memory are used when in fact they are not - after too many leaks your memory might be used up by false memory entirely and you won't be able to do anything with it.
However, "C++" (effectively meaning "the compiler") takes care of everything that you allocate on the stack, like
myclass obj;
as long as your destructors actually correctly deletes anything which you dynamically create inside that class.
In practice however, if you leak memory, modern operating systems will take care of it and usually clean it up. Usually there's some system in place where the OS will be able to recognize what parts of the memory you actually used, and then simply free everything in there as soon as the application is terminated.
Memory leaks usually only really create problems when your application needs so much memory that it needs to correctly free up some from time to time, or when you continuously leak memory in a loop (like in games), on systems with limited memory (like consoles).

heap memory and OS at the exit of a process written in C++

I have a doubt about the role of the operating system in regards to a process lifetime right now. I am using Linux.
Suppose that I have an application that creates a set of objects in the heap using new. During the lifetime of the application I have no need to delete any of those objects except at the exit the application or on an exception before exiting to do the clean-up.
Suppose I don't call delete at the end of the application for all those objects, do usually the OS reclaim/free all the heap allocated to make it available again at the process exits? If the process exit because of an exception or call to return or exit, does this always occurs?
If this is true this means that if I don't call delete there won't be any impact on the OS or on the other applications running on a machine. Right?
I usually use boost shared pointers or use delete but I would like just to clarify this doubt in a OS/Linux context
Kind Regards
AFG
That is correct. Any leak of memory after the lifetime of a process on a protected mode operating system is as a really nasty bug in the kernel (sometimes processes crash).
Having said that, the simplest way to check for memory leaks is to ensure that the heap has exactly the same number of allocated cells at the end of execution as it has at the beginning of execution. If you do not delete on exit, you have no way of checking this and will never discover legitimate memory leaks.
Modern OSes reclaim all resources of a closed process. Not only memory, but also file handles, etc.
No fear, the OS reclaims all the memory. What you need to watch out for is leaving some persistent resources, such as files, in an indeterminate state.
Just FYI my programming language deliberately fails to free memory on exit by default: it's faster that way. However RAII is not permitted. In C++ if you use RAII then you need to take more care.
Fast answer is no damage for OS if program don't call destructors of created objects or not freeing memory or other OS handles. Maximum impact is lost part of files which program has written before exiting.
Therefore Herb Satter in their book write about technique that short-lived applications specially doesn't free memory and don't call destructors for maximum speed of execution.
But better that programs normally handles their used OS resources.
(Sorry for my English)
You need to be more careful with other resources like file handles, database connections, etc. However, all memory is definitely reclaimed.

Is leaked memory freed up when the program exits?

If I programmed — without knowing it — a memory leak, and the application terminates, is the leaked memory freed?
Yes, a "memory leak" is simply memory that a process no longer has a reference to, and thus can no longer free. The OS still keeps track of all the memory allocated to a process, and will free it when that process terminates.
In the vast majority of cases the OS will free the memory - as is the case with normal "flavors" of Windows, Linux, Solaris, etc. However it is important to note that in specialized environments such as various Real-Time Operating Systems the memory may not be freed when the program is terminated.
The OS executing your program usually does cleanup memory that is not freed explicitly and handles that are not closed explicitly, but this is not guaranteed by the C++ standard. You may find some embedded device that do not free up your memory leaks.
That being said Windows and all distros of Linux that I've ever seen do free up memory leaks.
You can easily create a huge loop of memory leaks though to test it out yourself. Watch your RAM usage grow and then close your program. You will see that the RAM usage goes back down.
Another consideration when using C++ is that if you aren't deleting your heap allocated memory then your destructors are also not being called. Sometimes you will have other side effects as well if your destructors aren't called.
Are you running on a desktop OS (Windows, Linux etc.)? If so, yes, in general the system will free any memory associated with the program when the program exits.
Usually, yes. Some systems support things like shared memory blocks that aren't automatically freed when a program exits though. Most still keep a reference count and delete it when all the programs that opened it exit, but a few don't (e.g., 16-bit Windows had a few types of items that would remain allocated even when nothing referred to them -- though it usually crashed for other reasons before enough of this accumulated to cause a problem...)
As far as I know, a modern operating system will free this memory once the program terminates.
Depends on what memory you leaked. Some memory can't be reclaimed by the OS. Most memory on most OSes however will be automatically reclaimed when the process exits.