Re: free'ing malloc'd structure with malloc'd members

Discussion in 'C Programming' started by ravi, Jul 30, 2004.

  1. ravi

    ravi Guest

    If you know you have allocated properly, then if you deallocate in a
    reverse order, you wont have a problem.

    Emmanuel Delahaye wrote:
    > John wrote on 30/07/04 :
    > > In the course of an assignment, I learned the hard way that I

    shouldn't try
    > > to free a malloc'd member of a malloc'd structure after having

    freed that
    > > structure (i.e., free( structure ); free( structure->bufferspace

    ) ).
    > >
    > > My question is, if I free just the structure, will the (e.g.)

    bufferspace be
    > > freed implicitly, or do I have to (as I currently am) free the

    members
    > > first?

    >
    > "All what have been done must be undone".
    >
    > IOW, yes, you have to free the innermost elements first. There is no
    > implicit automatic mecanism that frees the memory in C.
    >
    > That said, you can write a pair of function known as 'creator /
    > destructor' that helps to create / delete the objects properly and

    hide
    > some gory details the user is not supposed to deal with.
    >
    > myobj_s *myobj_create (void);
    > void myobj_delete (myobj_s *this);
    >
    > --
    > Emmanuel
    > The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
    >
    > "C is a sharp tool"
    ravi, Jul 30, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John
    Replies:
    13
    Views:
    681
  2. Bernard Liang

    sscanf'ing floats into structure members

    Bernard Liang, Jun 21, 2006, in forum: C Programming
    Replies:
    3
    Views:
    696
    Keith Thompson
    Jun 21, 2006
  3. jbholman
    Replies:
    19
    Views:
    867
    CBFalconer
    Sep 19, 2008
  4. Replies:
    0
    Views:
    397
  5. arnuld
    Replies:
    13
    Views:
    500
    Ben Pfaff
    Apr 14, 2009
Loading...

Share This Page