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
If you insist on using exit()
:
#include
int main(){
{
std::string myname("Are there any leaks?");
}
exit(0);
}
Also, when you return from main
the returned value becomes the application’s exit code. So if you want to pass an exit code, use return exitCode;
in main()
instead of exit
.
Regarding that part:
This also raise another question for me, is such a code harmful?
Yes, because it is a BAD programming habit.
The OS will clean up any memory you failed to release, so as long as you haven't managed to eat all system memory and the page file, you shouldn't damage the OS.
However, writing sloppy/leaky code might turn into habit, so relying on the OS for cleaning up your mess is a bad idea.