Memory leak C++

后端 未结 10 543
野趣味
野趣味 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:50

    In most cases, it's worth cleaning up after yourself, for the many good reasons already given: better maintainability, better utility from checking tools and so on.

    If there are other functional reasons to clean up, maybe your data is saved to a persistent store, then you have no choice - you must clean up (although you might want to reconsider your design).

    In some cases however, it may be better to just exit and "leak".

    At the end of a program, your process is going to exit. When it does so, the operating system will recover any memory allocated by your program and in some cases it can do this much more quickly.

    Consider a large linked list, where each node is dynamically allocated, and carries a substantial dynamically allocated structure. To clean this up you must visit each node and release each payload (which in turn may cause other complex structures to be walked).

    You may end up performing millions of memory operations to run through such a structure.

    The user wants to exit your program, and they sit there for 10s of seconds waiting for a bunch of junk processing to happen. They cannot possibly be interested in the result - they're quitting the program after all.

    If you let this "leak", the operating system can reclaim the entire block of memory allocated to your process much more quickly. It doesn't care about the structures and any object cleanup.

    http://blogs.msdn.com/b/oldnewthing/archive/2012/01/05/10253268.aspx

    Ultimately you must understand what your tools are telling you, to be sure you're using them properly.

提交回复
热议问题