Memory leak C++

后端 未结 10 558
野趣味
野趣味 2021-02-02 06:02

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

10条回答
  •  情话喂你
    2021-02-02 06:47

    To add a different opinion.

    Such code is not harmful hat all. The OS will care for everything when the process terminates. Everything else results in an unstable OS. Just ensure that your persistent data (files, ...) is consistent.

    To go a bit further and provocatively states, explicitly freeing memory on program exit can be harmful.

    1. Program exit takes longer (Did you ever get annoyed to wait for a program to exit until the computer shuts down?)
    2. The correct order of destruction is not always trivial, especially with 3rd party components (I remember some programs that likely crash on exit)
    3. The OS may not let you free memory after leaving main(*) and kill your program instead

    Do you risk this just to make Valgrind give you a specific output?(**)


    (*)

    #include
    using namespace std;
    std::string myname("Is there any leaks");
    int main() {
            exit(0);
    }
    

    (**) Well, of course the output of any memory analyzer is more useful without "noise". What about only freeing memory explicitly on exit in debug mode?

提交回复
热议问题