linked list problem

This is a discussion on linked list problem within the C Programming forums, part of the General Programming Boards category; i have this loop which is suppose to delete all nodes from the list and then free the memory that ...

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    4

    linked list problem

    i have this loop which is suppose to delete all nodes from the list and then free the memory that they occupy. could somebody check what is wrong with it. im kinda lost here. thanks in advance

    Code:
    for (p=first; p!=NULL; p=p->next)
       free(p);

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    You are freeing p and then the for loop has to do a p=p->next operation. How can you say p=p->next when p is gone? A possible solution is to use a temp pointer:

    Code:
    for (p=first; p!=NULL; )
    {
        node* temp = p->next;  // Use whatever pointer type needed in place of 'node'
        free(p);
        p = temp;
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help sorting a linked list. Beginner
    By scarlet00014 in forum C Programming
    Replies: 1
    Last Post: 09-27-2008, 06:16 PM
  2. singly linked circular list
    By DarkDot in forum C++ Programming
    Replies: 0
    Last Post: 04-24-2007, 08:55 PM
  3. Replies: 6
    Last Post: 03-02-2005, 01:45 AM
  4. Linked list with two class types within template.
    By SilasP in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2002, 05:13 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM

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