1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Memory Leakage

Discussion in 'C' started by manaila, Jul 12, 2011.

  1. manaila

    manaila New Member

    Joined:
    Jul 6, 2010
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    On Earth
    Hi,
    I am developing an embedded system using C. I have a limited memory, so I sometimes run into a problem whereby my system becomes totally trashed due to memory leakage.
    So I am asking for suggestions and recommendations about the sources of memory leakage and how I can avoid them.
     
  2. seangtz

    seangtz New Member

    Joined:
    Jun 6, 2008
    Messages:
    126
    Likes Received:
    3
    Trophy Points:
    0
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    Make sure that *EVERY* memory allocation is matched by a memory free, WITHOUT EXCEPTION.
    Then it won't leak.
     
  4. manaila

    manaila New Member

    Joined:
    Jul 6, 2010
    Messages:
    11
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    On Earth
    I wish want to further the discussion. When we have something like this:
    Code:
    char myFunc(char* a, char* b)
    {
        ...
    }
    
    then, do we still have to make memory deallocation?
     
  5. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    There is one situation where you need to free memory, which is where you have allocated it. If you have allocated it then you MUST deallocate it (when you've finished with it). If you have not allocated it then you MUST NOT deallocate it. That's all there is to it.

    It's good practice to allocate and deallocate memory within the same function wherever possible, e.g.:
    Code:
    void doSomething()
    {
      struct summat *newThing = malloc(sizeof(struct summat));
      do_something_else(newThing);
      free(newThing);
    }
    
    If this isn't possible then it's a good idea to hand off memory management responsibility to a memory management class or family of functions, which would encapsulate the handling of that memory and make it all fairly easy to find, compared with splattering malloc calls all over the place.
     
  6. StarDrago

    StarDrago New Member

    Joined:
    Nov 12, 2011
    Messages:
    49
    Likes Received:
    2
    Trophy Points:
    0
    u can use deleaker or similar debugger for search gdi and memory leaks.
     

Share This Page