Thread: help on linked list and memory leak

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    64

    help on linked list and memory leak

    hello all,

    I created a linked list like this:
    Code:
    struct storedata
    {
        int      iData;
        char   cData;
        struct storedata *next;
    } datastore;
    to store data the size of which may varies from time to time.

    And I tried to free memory that allocated by malloc() before program quits. The confusion here is I only free the pointers of every nodes like this:
    Code:
    void freelist(struct storedata *tobefreed)
    {
        struct storedata * tmp;
        while(tobefreed != NULL)
        {
            tmp = tobefreed->ptr;
            free(tobefreed);
            tobefreed = tmp;
        }
    }
    But a tutorial says every member in the struct also needs to be freed, like this:
    Code:
    void freelist(struct storedata *tobefreed)
    {
        struct storedata * tmp;
        while(tobefreed != NULL)
        {
            tmp = tobefreed->ptr;
    
            //-- added lines [begin] --
            free(tobefreed->iData);
            free(tobefreed->cData;
            //-- added lines [end] --
    
            free(tobefreed);
            tobefreed = tmp;
        }
    }
    If it is true, why? I only allocated memory for pointer node, not for members it contains.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > free(tobefreed->iData);
    Only if the members themselves are pointers which you allocated with malloc.

    In this case, they're not pointers, so there is no free on an individual member. They all disappear at the same time when you free the pointer to the whole struct.

    malloc and free calls should balance exactly.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2004
    Posts
    64
    thank you salem,

    that is exactly what i guessed. now it's been made sure.

    thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unknown memory leak with linked lists...
    By RaDeuX in forum C Programming
    Replies: 6
    Last Post: 12-07-2008, 04:09 AM
  2. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  3. Problem with linked list ADT and incomplete structure
    By prawntoast in forum C Programming
    Replies: 1
    Last Post: 04-30-2005, 01:29 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM