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?
Yes, all memory is returned.
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.
“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.
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).
The operating system cleans up all used memory and file handles when a process is terminated for whatever reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With