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

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).

Related

Why do I get SIGKILL instead of std::bad_alloc? [duplicate]

I'm developing application for an embedded system with limited memory (Tegra 2) in C++. I'm handling NULL results of new and new[] throughout the code which sometimes occurs but application is able to handle this.
The problem is that the system kills the process by SIGKILL if the memory runs out completely. Can I somehow tell that new should just return NULL instead of killing the process?
I am not sure what kind of OS You are using, but You should check if
it supports opportunistic memory allocation like Linux does.
If it is enabled, the following may happen (details/solution are specific to the Linux kernel):
Your new or malloc gets a valid address from the kernel. Even if there is not enough memory, because ...
The kernel does not really allocate the memory until the very moment of the first access.
If all of the "overcommitted" memory is used, the operating system has no chance but killing one of the involved processes. (It is too late to tell the program that there is not enough memory.) In Linux, this is called Out Of Memory Kill (OOM Kill). Such kills get logged in the kernel message buffer.
Solution: Disable overcommitting of memory:
echo 2 > /proc/sys/vm/overcommit_memory
Two ideas come to mind.
Write your own memory allocation function rather than depending on new directly. You mentioned you're on an embedded system, where special allocators are quite common in applications. Are you running your application directly on the hardware or are you running in a process under an executive/OS layer? If the latter, is there a system API provided for allocating memory?
Check out C++ set_new_handler and see if it can help you. You can request that a special function is invoked when a new allocation fails. Perhaps in that function you can take action to prevent whatever is killing the process from executing. Reference: http://www.cplusplus.com/reference/std/new/set_new_handler/

Heap memory clearance when application closes abruptly

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.

dynamically allocated memory after program termination

When a C/C++ program containing the dynamically allocated memory(using malloc/new) without free/delete calls is terminated, what happens to that dynamically allocated memory?
Does the operating system takes back the memory or does that memory becomes unaccessible to other programs?
I don't think that there are any guarantees in the language standard, but modern operating systems which support sparse virtual memory and memory protection (such as MacOS X, Linux, all recent version of Windows, and all currently manufactured phone handsets) automatically clean up after badly-behaved processes (when they terminate) and free the memory for you. The memory remains unavailable, however as long as the program is running.
If you're programming on microcontrollers, on MacOS 9 or earlier, DOS, or Windows 3.x, then you might need to be concerned about memory leaks making memory permanently unavailable to the whole operating system.
Most modern operating systems employ a memory manager, and all userland processes only see so-called virtual memory, which is not related to actual system memory in a way that the program could inspect. This means that programs cannot simply read another process's memory or kernel memory. It also means that the memory manager will completely "free" all memory that has been assigned to a process when that process terminates, so that memory leaks within the program do not usually "affect" the rest of the system (other than perhaps forcing a huge amount of disk swapping and perhaps some "out of memory" behaviour).
This doesn't mean that it's in any way OK to treat memory leaks light-heartedly, it only means that no single program can casually corrupt other processes on modern multi-tasking operating systems (deliberate abuse of administrative privileges notwithstanding, of course).
Short answer: yes, the OS will free this memory.
Most operating systems will free this memory, however it is bad practice to rely upon this behaviour. Some operating systems will not free this memory. For example, embedded systems. For portability, always free all the memory you allocate.
C/C++ doesn't have garbage collection feature. If you allocate memory and doesn't free it up, it's of no use while the program execution continues. This is called memory leak. Once the execution finishes, OS takes back this memory and is again available for use.
During the program's execution, you cannot count on the operating reclaiming the memory. That would be a garbage collection feature found in many other languages such as Java and C#. While garbage collected c++ is possible, I don't believe any mainstream implementations use it.
On the other hand, once your program completes its execution, the OS should reclaim the memory used by the program. So during execution the memory remains off-limits, but is accessible again after the program exits.

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.