check null structs

This is a discussion on check null structs within the C Programming forums, part of the General Programming Boards category; Hi friends!! I am developing an application which uses dynamic lists, with structures as nodes. I allocate structures with malloc(), ...

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    3

    check null structs

    Hi friends!! I am developing an application which uses dynamic lists, with structures as nodes. I allocate structures with malloc(), and free them with free(). But when I free a struct with free, the struct is not pointing to null.

    Code:
    struct mystruct *node=malloc(sizeof(mystruct));
    .
    .
    free(node);
    if(node==NULL)printf("node null");
    else printf("node not null");
    So here it always print "node not null". My question is, how can i check that a structure has been freed with free?

    Thank you very much!!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,310
    After the free, set node to NULL.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Nope it doesn't... free() simply releases the memory back into the computer's resource pool. It does not reset the pointer.

    The simplest way around that is with a wrapper function...
    Code:
    node* MyFree(node* target)
      {  
         free(target);
         return NULL;
      }
    
    
    // call as...
    ThisNode = MyFree(ThisNode);
    OR...
    Code:
    void MyFree(node** target)
      {
         free(*target);
         *target = NULL;
       }
    
    // call as
    MyFree(&ThisNode);
    Whichever makes the most sense in your code...

  4. #4
    Registered User
    Join Date
    Jan 2012
    Posts
    3
    Ok i will follow your advice. Thanks to everyone!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Check if string is null
    By doubty in forum C Programming
    Replies: 3
    Last Post: 07-04-2009, 03:10 PM
  2. How check a variable is null?
    By 6tr6tr in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2008, 07:36 AM
  3. Check if a cin is null
    By HumbuckeR in forum C++ Programming
    Replies: 6
    Last Post: 04-16-2006, 08:16 AM
  4. null struct to terminate array of structs?
    By eccles in forum C Programming
    Replies: 6
    Last Post: 01-24-2005, 05:27 AM
  5. problem with Structs/NULL
    By peking1983 in forum C Programming
    Replies: 1
    Last Post: 01-31-2003, 05:22 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21