Deleting from linked list

This is a discussion on Deleting from linked list within the C Programming forums, part of the General Programming Boards category; I've been working my way through SAMS teach yourself C for Linux programming over the last year and have recently ...

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    14

    Deleting from linked list

    I've been working my way through SAMS teach yourself C for Linux programming over the last year and have recently been studying linked lists.

    To delete from the middle of a linked list the book says to do this:

    struct person *current1, *current2;

    You should go through the list until current1 points to the element before the one you want to delete then:

    current2 = current1->next;

    current2 now also points to the element.


    free(current1->next);
    current1->next = current2->next;

    What I am not understanding though is the above. current2 points to the memory current1->next points to, when you free current1->next you are deallocating the memory that current2 points to and current2->next would havel be stored here so how can you be expected to you assign current current2->next to current1->next if you have dellocated the memory current2 points to?
    Last edited by Golf7; 06-20-2010 at 02:32 PM.

  2. #2
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,629
    Ugh. Idiotic book.
    You're right in this case. You should update the pointer before calling free. Otherwise you will be invoking undefined behavior.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  3. Problem with linked list ADT and incomplete structure
    By prawntoast in forum C Programming
    Replies: 1
    Last Post: 04-30-2005, 01:29 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 09:33 PM
  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