Thread: using free on structures with pointers to data types inside

  1. #1
    Climber spoon_'s Avatar
    Join Date
    Jun 2002
    Location
    ATL
    Posts
    182

    using free on structures with pointers to data types inside

    Code:
    struct hostent {
        char FAR *       h_name;
        char FAR * FAR * h_aliases;
        short            h_addrtype;
        short            h_length;
        char FAR * FAR * h_addr_list;
    };
    That is how the structure hostent is declared. Now, if I do this:

    Code:
    struct hostent *winfo = NULL;
    ....
    some code that puts info into winfo
    ....
    free(winfo)
    are the three pointers (h_name, h_aliases, h_addr_list) freed also?

    thanks,
    spoon_

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>are the three pointers (h_name, h_aliases, h_addr_list) freed also?
    No. If you malloc() it, you must free() it.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,380
    Your pointer winfo points to a piece of memory which contains an object of type struct hostent. The pointer-members of this struct each point to a piece of memory. If you release only the memory winfo points to, you only release the block of memory which contains the object of type struct hostent. But you don't release the blocks of memory where the pointer-members of that object pointed to.

    So before releasing the object, you should first release the memory the pointer-members are pointing to.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Generic Pointers to structures
    By dunxton in forum C Programming
    Replies: 8
    Last Post: 02-20-2009, 10:23 AM
  2. Replies: 8
    Last Post: 12-05-2008, 02:18 AM
  3. Replies: 4
    Last Post: 06-14-2005, 05:45 AM
  4. C Programming Question
    By TK in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 07-04-2002, 07:11 PM
  5. Freeing pointers in structures
    By jim50498 in forum C Programming
    Replies: 4
    Last Post: 03-08-2002, 12:53 PM