I just wrote a code in C++ which does some string manipulation, but when I ran valgrind over, it shows some possible memory leaks. Debugging the code to granular level I wrote a
#include<iostream>
using namespace std;
int main()
{
{
std::string myname("Is there any leaks");
}
exit(0);
}
This also raise another question for me, is such a code harmful?
#include<stdio.h> int main() { char *p=(char *)malloc(sizeof(char)*1000); exit(0); }
It's not harmful on modern operating systems, because they will close all resources owned by a process automatically when the process ends.
However, it's still bad practice, and might lead to subtle and hard to find errors when, over several years of maintenance, the code slowly changes until, on day, this does become harmful. I have worked in projects where some of the code was a decade old and I have learned a few lessons doing so, some of them rather harsh. Therefore, I would avoid writing such code, even if it currently doesn't pose a problem.
At the time your process is actually exiting, as when main() exits, the OS will reclaim all resources allocated to your application either way. How you exit isn't so important - at least with regard to dynamic memory.
If you have some distributed database connection open or something, you should use atexit() handlers to close it, and forceful termination with straight-up exit may make them not run which would be bad - but as far as your OS resources are concerned you're probably okay.
You should also always make sure you release (manual) file locks and similar things as they may not go away due to a process exit.
If the program is exiting, you do not have to worry about memory which was allocated with malloc
or new
. The OS will take care of it - anything in your process' virtual address space exclusively will go away when the process dies. If you're using shared memory or named pipes it could still be a concern.