Memory Leaks

Discussion in 'Mac Programming' started by Duke Leto, May 20, 2008.

  1. Duke Leto macrumors regular

    Mar 17, 2008
    I know about memory management (I do not fully understand it, but I use pointers and release my data when I need to), but when I ran my application under Instruments and found memory leaks (which I expected because I am not a programmer with the best practices in the world) I realized that I really did not know what caused memory leaks.

    Is it forgetting to release an object? Is it a bad dealloc() function? What are some common causes for memory leaks?

    Here I basically ask what caused memory leaks in your previous experience.
  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    there are a lot of things in the C world that can result in memory leaks. In my experience the more difficult things are libraries that have a protocol you must follow to avoid leaks. For example, if you run a DB query in a loop, and the library itself allocates memory for the result set, you normally have to make a call to the library to indicate that you are done with that result so the memory can be freed.

    If you are dealing with an object pointer, and you are pointing to something that is not autoreleased, it's easy to assign a new object pointer without freeing the first.

    Again, with objects that are not autoreleased, if one object points to another, and the destructor of the first doesn't destroy the second you can get into trouble.

    Obviously mallocing without freeing will also leak. This is why there are libraries that provide smart pointers that help you manage allocation and deallocation.

    When you are using GC and autoreleased objects, leaking references is the same as leaking memory, and this can be more subtle.

    I'm sure there are dozens of other ways, but these are the ones I can think of immediately.

  3. yeroen macrumors 6502a


    Mar 8, 2007
    Cambridge, MA
    Unfortunately, it's never as straightforward as the following scenario:

    void *ptr = malloc (NUM_BYTES_TO_LEAK);
    ptr = NULL;

    In my experience, most memory leaks have been the result of not minding the fact that some library call that returns a dynamically allocated chunk of memory also puts the burden on you for freeing that memory. This is common in C and C++ string handling routines, for example.

    A more insidious example is in C++ if an exception gets thrown from a constructor after some memory has been dynamically allocated, but referents to that memory, e.g. a private member that's a raw (vs a smart) pointer, don't know how to clean up their part of the mess before the half-constructed object is in ashes.

    A good reference for memory leaks and their debugging in C and C++ is:
    Memory as a Programming Concept in C and C++

Share This Page