Thread: How to properly free a pointer and its allocated memory

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    26

    Question How to properly free a pointer and its allocated memory

    Hi all:

    I have declared a pointer as following:

    char *stringPtr = NULL;
    stringPtr = malloc(10);

    After I finish with it,

    free(stringPtr);

    Do I need to put up another line:

    stringPtr = NULL;

    Thank you

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    You don't need to. Though, if you free stringPtr, stringPtr is NOT set to NULL. So if you want also to set it to NULL and not just free the memory (which helps in some occasions) then you can add the line strPtr = NULL

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Basically, the rule is "if the pointer is still available, then set it to NULL". If the pointer is local to a function, and you have a free at the very end of the function, then you don't need to set the pointer to NULL.

    If you often find yourself writing:
    Code:
    free(ptr);
    ptr = NULL;
    you could make a function:
    Code:
    freeAndNull(void **ptr)
    {
       free(*ptr);
       *ptr = NULL;
    }
    
       char *p;
       p = malloc(...);
    ...
       freeAndNull(&p);
    ...
    Edit: Re-reading the subject of the post: You do not "free" a pointer. You free the memory associate to that pointer. [Of course, you can have a pointer to pointer situation where the first level pointer is also allocated, in which case you'd have to do (at least) two free operations, but it still applies that the original pointer is not freed].


    --
    Mats
    Last edited by matsp; 09-16-2008 at 06:28 AM.
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed