Doubt related to free()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sathishc58
    New Member
    • Sep 2007
    • 34

    Doubt related to free()

    Hi All
    I have a question related to free().

    For example
    A(char *buffer) call B(char *buffer)
    B(char *buffer) in turn calls C(char *buffer)
    C(char *buffer) in turn calls D(char *buffer)
    D(char *buffer) in turn calls E(char *buffer)
    and so on.........
    I pass a pointer as a parameter from A()
    A(char *buffer);
    1) This buffer was freed somewhere in some function. (Deallocation could have done by B() or C() or D() or E() etc)
    2) I did not set BUFFER=NULL after freeing up the buffer in any of the function.

    Is there any way to know whether buffer was FREED or NOT when I return to A().
    I believe BUFFER will be pointing to the location even if we free() the data.

    Please let me know your response.

    Thanks & Regards
    Sathish Kumar
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Yep, the value of the buffer pointer isn't altered but it doesn't point to a valid memory region anymore; you have freed it so you can't use it anymore.

    kind regards,

    Jos

    Comment

    • gpraghuram
      Recognized Expert Top Contributor
      • Mar 2007
      • 1275

      #3
      Hi,
      As Jos said it will be an invalid memory.
      But if u want to find if there is a leak in code then go for Purify or boundschecker

      raghu

      Comment

      • Tassos Souris
        New Member
        • Aug 2008
        • 152

        #4
        You probably must get used to using pointer to pointers rather than pointers. For example when you have the head of a single linked list it is better to use that:
        Code:
        void freeList( struct List **head ){
            // Do the free of all the nodes here
            
            // Set it safely to NULL
            *head = NULL;
        }
        You must make it a rule that every free() is followed by a assignment to NULL:
        Code:
        free( ( void * )ptr );
        ptr = NULL;

        Comment

        Working...