Memory leak C++ Memory leak C++ c c

Memory leak C++


Use return 0; instead of exit(0); at the end of main. The use of exit circumvents the execution of the destructors.


If you insist on using exit():

#include<iostream>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.


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.