Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Prevent memory leakage from coding

  1. Oct 24, 2012 #1
    I am studying a problem releated to memory leakage.
    Now, there are many tools to check memory leak at run-time (dynamic analysis), and some tools can check memory leakage at compile-time (static analysis). But I have some questions:
    How do you think to prevent memory leakage from coding phase (without using tool)? (or In coding phase, what do you have to do to prevent memory leakage?)
    I want to investigate from many programmers in many countries.
    Last edited: Oct 24, 2012
  2. jcsd
  3. Oct 26, 2012 #2


    User Avatar
    Science Advisor

    Re: memory leakage

    Hey JulsSmile and welcome to the forums.

    The simple solution that is used is to centralize memory allocation in one place and then use a variety of sub-systems that interface with your common code to create structures.

    The basic approach that is commonly used is something known as a class factory.


    What you can do with a class factory is behind the interface, you keep track of what has been created and store the pointers for all new allocated structures in that factory and the factory can do things like take class types and other information to return either a direct pointer to that instance or an interface pointer that lets you access the class instance from that interface.

    If you use an interface pointer then it means that what you can do is let the factory deal with the real pointer so that it can do things like delete it (without the programmer doing it or trying a double delete), lock the resource (good for multi-threading) amongst other things.

    Within the factory you can add an event system that broadcasts messages of when instances have been deleted, instantiated (created), modified, locked, and so on and every other thing that accesses the resource can update itself accordingly.

    So not only do you take care of memory leakage, you also take care of synchronization between every single module that uses shared data.
  4. Nov 26, 2012 #3
    Re: memory leakage

    Thanks for the answers! I'm curious to know what you prefer debuggers for Linux and for Windows?
    Perhaps you prefer another methods?
  5. Nov 26, 2012 #4


    User Avatar
    Homework Helper

    Re: memory leakage

    For Windows, you can download and use microsoft visual C / C++ express which is free.

    Getting back to your original question, I'm not sure there is some univeral method to avoid coding problems, whether the coding problems involve memory leakage or other issues. This is why we use debuggers and other coding tools.
  6. Nov 26, 2012 #5

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Re: memory leakage

    There is something that comes pretty close. Don't use raw pointers.
    • Use std::string rather than char*.
    • Use a STL container rather than a dynamically-allocated C-style array.
    • Use smart pointers such as C++11's std::unique_pointer or those from Boost if you don't have C++11.
    • If you are doing low-level programming and need to allocate memory, follow RAII religiously (wiki article: http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization).
    • Follow the rule of three (C++: rule of five) as well.

    This won't stop the worst kind of memory leaks. Plug all the leaks reported by a tool such as valgrind and your program may still "leak." Use a language such as Java, C#, lisp, python, etc., that does automated garbage collection and your program may still "leak."

    These most insidious of leaks are hard to find because the program has valid references to the memory throughout execution and because the memory is properly freed right before the program terminates. The problem is that the program should have severed those links / let variables go out of scope / deleted the allocated memory once there is no longer a need to keeping that old allocated memory around.
  7. Nov 27, 2012 #6


    User Avatar
    Gold Member

    Re: memory leakage

    I'm a Linux guy, gdb and valgrind are staples.

    Judiciously placed printfs are also pretty useful.
  8. Nov 27, 2012 #7
    Re: memory leakage

    Oh! I know valgrind - the best tool for Linux! I want to know debuggers for windows ))
  9. Nov 28, 2012 #8
    Re: memory leakage

    Hi all!
    I can give some good debuggers that I use: purify, deleaker, memcheck.
  10. Nov 30, 2012 #9
    Re: memory leakage

    How about vld. Is there someone who use it?
  11. Apr 2, 2013 #10
    This tool is often used by beginners.
    I can posovetovt use built-in tools to detect leaks. They do not provide 100% protection, but they can help find memory leaks.
  12. Apr 2, 2013 #11

    jim mcnamara

    User Avatar

    Staff: Mentor

    There are C libraries like dmalloc that are meant specifically to debug both memory allocation and memory management.
  13. Apr 3, 2013 #12
    Thanks for answers. I have already finished my researches.
    But I have a new question - how to avoid memory leaks in my code? I read about memory management and there are a few tips. I'm interested in what you are doing to avoid leaks?
  14. Apr 3, 2013 #13
    Avoiding memory leaks with C

    Most the code I've worked on (which is in C and at three different companies) uses a standard format to reduce the chances of memory leaks. The form involves:
    1. Free memory at the same level of the function heiarchy it was allocated in.
    a. If you have a create function, then have a delete.​
    b. If CreateFoo, calls CreateBar, then have a DeleteFoo that calls DeleteBar.​
    2. If an error happens in a function, free all memory allocated by that function before returning. [see example]
    a. If the erorr happens in CreateFoo, try to use DeleteFoo to do the cleanup. Or a helper function that is also used by DeleteFoo.​
    b. Use separate variables for the local object creation from the pointers used to return an object.​
    3. Make all the error handling in each function as similar to other functions as possible.
    Last edited: Apr 3, 2013
  15. Apr 3, 2013 #14


    User Avatar
    Homework Helper

    What I often do is have a single exit point for a function that releases any potentially opened or allocated resource:

    Code (Text):

        handle = INVALID_HANDLE_VALUE; /* initialize handles to invalid */
        ptrtomem = NULL;  /* initialize pointers used for allocation to NULL */

    /* ... */

    common_exit: /* close or free any open or allocated resources */
        if(handle != INVALID_HANDLE_VALUE)
        if(ptrtomem != NULL)
  16. Apr 4, 2013 #15


    User Avatar

    Staff: Mentor

    It doesn't help with memory leakage, but to help myself clean things up I often initialize all pointers to NULL first (just like rcgldr did in his code), then delete them using

    Code (Text):
    #define DELETEPTR(__ptr__) { if (__ptr__) { delete __ptr__; __ptr__ = NULL; }}
    This way I don't have to care about when the program stopped to work and which objects were already created.
  17. Apr 4, 2013 #16
    Do not use dynamic memory
  18. Apr 4, 2013 #17


    User Avatar
    Homework Helper

    Yes, I forgot to mention that if one of my programs does any closing of handles or freeing of memory within the program (versus at the exit point), I also have to set handle values back to INVALID_HANDLE_VALUE after closing and pointers back to NULL after freeing memory. Borek's idea of using a macro to do both seems like a good idea, for handles it could be:

    Code (Text):
    #define CLOSEHANDLE(__hdl__) \
      { if (__hdl__ != INVALID_HANDLE_VALUE) \
          { close(__hdl__); \
            __hdl__ = INVALID_HANDLE_VALUE; }}
  19. Apr 5, 2013 #18
    I am very grateful!
    Many thanks to ScottSalley!!!
    Your explanation I printed and hung at the computer!
  20. Apr 21, 2013 #19


    User Avatar
    Gold Member

    What I do to avoid memory leaks is use .NET. It is really pretty difficult to crash a machine using the .NET libraries, and it has very good performance. It is also available for Linux. I did program extensively in C for many years, and my belief is, no matter how "good" you are, how "good" your tools are, and how "good" your design is, if you use C or C++ and program directly in the OS's libraries, you WILL sooner or later get a memory leak, and it may take you a long time to realize it.

    Alternatively, you could use Java--or any strongly typed, modern language besides C or C++.
  21. Apr 22, 2013 #20
    Thanks for the advice. But even in Java garbage collector does not solve the problem with memory leaks completely.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook