Thread: identify bug in code

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    21

    identify bug in code

    List points to the first element in the list.
    All the nodes is intended to be allocated with malloc.

    The task is to insert the integer toinsert into the list before the node containing before. And return the list resulting from the insertion.

    Code:
    typedef struct dlintlist_struct dlintlist_t;
    
    
    struct dlintlist_struct {
    int item;
    dlintlist_t *next;
    dlintlist_t *prev;
    
    
    };
    
    
    dlintlist_t *insert(dlintlist_t *list, int before, int toinsert) {
    
    
    dlintlist_t *new_node;
    while (list != NULL && list->item != before) {
    
    
    list = list->next;
    
    
    }
    
    
    if (list != NULL) {
    
    
    new_node = malloc(sizeof(dlintlist_t));
    new_node->prev = list->prev;
    new_node->next = list;
    list->prev->next = new_node;
    
    
    }
    
    
    return list;
    }
    There are 3,4 bugs in this code which I have to identify.

    1. As you've traversed through list you lose track of the first pointer.
    2. The number toinsert hasn't actually been inserted.
    3. The declaration of typedef is incorrect as the structure dlintlist_struct hasn't yet been declared at that point.

    I was expecting an error somewhere between the if statement, but I drew out the pointer diagram and I found it to be correct.

  2. #2
    Registered User
    Join Date
    Apr 2012
    Posts
    21
    Please ignore this as I've found the others.

    malloc wasn't checked to see if it returned a NULL pointer and line 17 should be
    "list->next != NULL".

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. identify problems with code
    By acpower in forum C Programming
    Replies: 5
    Last Post: 06-07-2012, 05:57 AM
  2. Need help to identify basic wrong code
    By anik18 in forum C Programming
    Replies: 2
    Last Post: 06-14-2011, 09:25 PM
  3. can you identify this car?
    By axon in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 07-19-2004, 02:59 PM