Thread: free (p)

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    6

    Question free (p)

    When you declare a *p, assign memory to it

    p = (char*)malloc(5*sizeof(char));

    and then release it

    free (p);

    itīs recommended to do the following:

    p = NULL;

    right?

    If this is recommended then why doesnīt the "free" function already includes this assignment inside?

    Thanks.

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Because there is no requirement to do so.

    If you want you can make your own:

    Code:
    void *myfree(void *ptr)
    {
      free(ptr);
      return NULL;
    }

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > If this is recommended then why doesnīt the "free" function already includes this assignment inside?
    Because pointers (like everything else) are passed by value

    Code:
    void myfree ( void *ptr ) {
       free( ptr );
       ptr = NULL;
    }
    
    
    int main ( ) {
        char *p = malloc( 10 );
        myfree( p );
        /* p won't be NULL here, but it will have been freed */
    }

    If you want a myfree which does reset the pointer, then you need to do this
    Code:
    void myfree ( void **ptr ) {
       free( *ptr );
       *ptr = NULL;
    }
    
    
    int main ( ) {
        char *p = malloc( 10 );
        myfree( &p );
    }
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 06-24-2005, 04:27 PM
  2. Help needed with backtracking
    By sjalesho in forum C Programming
    Replies: 1
    Last Post: 11-09-2003, 06:28 PM
  3. "if you love someone" :D
    By Carlos in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 10-02-2003, 01:10 AM
  4. SIGABRT upon free()
    By registering in forum C Programming
    Replies: 2
    Last Post: 07-19-2003, 07:52 AM