Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a c++ program automatically free memory when it crashes?

I read in Google c++ coding standards that Google does not use exception. If exception is not used, how do you free memory when errors occur in your program?

For example, f() calls g(), and if there is error in g(), I should free all memory allocated in g(), and then call an exception to f(). Once f() catches the exception, f() will free all memory allocated in f(), and exits the program.

If exception is not used, and if there is an error in g(), can I force exit exit(0), and will the c++ program be smart enough to free all memory that is allocated? My guess is, since c++ maintain a stack and heap, and once the program exits, c++ will automatically free both stack and heap?

like image 633
Michael Avatar asked Sep 19 '11 14:09

Michael


People also ask

Does C free memory on exit?

Yes, all memory is returned.

What happens to the allocated memory after a program exits?

The memory is reclaimed by the Operating system once your program exits. The OS doesn't understand that your program leaked memory, it simply allocates memory to the program for running and once the program exits it reclaims that memory.

What does freeing memory do in C?

“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

Do memory leaks go away when the program ends?

Once the memory has been leaked, it's gone for as long as the program is running. Or it wouldn't be a leak. But, if you're referring to the computer system's memory, the answer is: No. Memory is reclaimed when the leaking program ends (perhaps due to crashing once out of memory).


1 Answers

The operating system cleans up all used memory and file handles when a process is terminated for whatever reason.

like image 169
grep Avatar answered Oct 05 '22 11:10

grep