free() and struct

This is a discussion on free() and struct within the C Programming forums, part of the General Programming Boards category; Ok all you pro's here's another question that's got me thinking and I can't find any answers in my books. ...

  1. #1
    Nosepicker DrakkenKorin's Avatar
    Join Date
    Nov 2001
    Posts
    407

    free() and struct

    Ok all you pro's here's another question that's got me thinking and I can't find any answers in my books.

    Lets say we have a struct defined below:

    Code:
    typedef struct studentType
    {
         char *first;
         char *last;
         struct studentType *next
    } student;
    
    typedef student *studentPtr;
    Now lets say I got me a pointer (lptr) pointing to any studentPtr, and lets also say that I want to free() said pointer.

    Now iff I use
    Code:
    free(lptr);
    Will that also free up the memory that was malloc'ed for those char pointers?

    I have always been under the impression that when you use
    free(), especailly on a struct, it will free() up everything, included the memory reserved within the struct.

    If you're not following, let me know and I'll post the question and my answer (was on an exam) and where I lost points.

    Thanx!
    DrakkenKorin

    Get off my Intarweb!!!!

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    No, it won't. It will only free the memory allocated for the structure, not the memory allocated for whatever it's ponters point at.

    If this were the case, you'd free your entire linked list by simply:

    free( topNode );

    This would be a "BadThing(TM)".

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Nosepicker DrakkenKorin's Avatar
    Join Date
    Nov 2001
    Posts
    407
    Dang, there goes my A.

    But that's what happens when I start thinking too hard. That's it, no more thinking for me!

    Thanx anyway Quzah
    DrakkenKorin

    Get off my Intarweb!!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Looking for a way to store listbox data
    By Welder in forum C Programming
    Replies: 20
    Last Post: 11-02-2007, 12:48 AM
  2. Replies: 10
    Last Post: 05-19-2006, 12:23 AM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 04:00 PM
  4. Bi-Directional Linked Lists
    By Thantos in forum C Programming
    Replies: 6
    Last Post: 12-11-2003, 10:24 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 02:27 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21