usage of free in double linked lists?

Discussion in 'C' started by gaiety, Mar 25, 2009.

  1. gaiety

    gaiety New Member

    Joined:
    Mar 25, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    usage of free in double linked lists
    can i free a pointer which i got through assignment of some other pointer
    suppose p and q are pointers of same type then
    after doing p=q;
    is it necessary to use free(p) and free(q) or only one is enough


    Thanks in advance
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    You free the memory pointed to by the pointer, not the pointer itself. There is no magic connection between a pointer and the memory it points to, so
    Code:
    char *x=malloc(20);
    char *y=x;
    free(y);
    
    is perfectly valid (but watch out because x is no longer pointing to valid memory).

    If you want to free the pointer itself then you need to make the variable of type pointer to pointer to thing, not just pointer to thing:
    Code:
    char **x=malloc(sizeof(char*));
    *x=malloc(20);
    char *y=*x;
    free(*y); // frees the 20 bytes
    free(y); // frees the pointer
    
    You must not free the same memory twice
    Code:
    char *x=malloc(20);
    char *y=x;
    free(y); // OK, the 20 bytes are deallocated now
    free(x); // likely to crash your program
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice