Search code examples
c++linked-listfreedelete-operator

Why can't I use 'delete' for this line?


I've started to learn linked lists today, and I am trying to delete nodes.

void deleteEnd(Node* refNode) {
    Node* lastNode;
    lastNode = new Node;

    while((refNode->next)->next != NULL) {
        refNode = refNode->next;
    }
    lastNode = refNode->next;

    refNode->next = NULL;
    delete lastNode;
}

void deleteIndex(Node* refNode, int index) {
    Node *prev, *next, *deleted;
    prev = new Node;
    next = new Node;
    deleted = new Node;

    for(int i=1; i < index; i++) {
        refNode = refNode->next;
    }

    prev = refNode;
    deleted = prev->next;
    next = deleted->next;

    prev->next = next;
    free(deleted);
}

I can use delete in the first one, but when I try to use it in the second, it doesn't work. The terminal doesn't give any error messages.

I found some information on the Internet, but I couldn't really understand it.

This is my linked list:

class Node {
public:
    int data;
    Node *next;
};

Solution

  • As pointed out by the comments, there are several things wrong with this code. All issues are from the comments, none are found by me, all credit goes to François Andrieux, Jesper Juhl, Sven Nilsonn, Avi Berger, and Thomas Matthews.

    First, the code probably doesn't work because you mixed new and free. new is a C++ API function, while free is from C. Whenever you construct an object with new, which should not be that often with C++'s automatic memory management, you must free it with delete.

    Second, when looping through a list, always start at 0. The only reason otherwise would be to start at the second item.

    Third, in this passage:

    prev = new Node;
    ...
    prev = refNode;
    ...
    prev->next = next;
    

    When you set prev, it is overwriting the previous value. If this is a pointer, as it is, then this causes a memory leak. Always delete it before overwriting.

    Finally, in deleteEnd, as pointed out by Thomas Matthews, you are trying to dereference, or get the value from, the pointers, without checking if it is nullptr. If one is, it will cause undefined behavior, and can crash the program.