Search code examples
cdata-structuresdoubly-linked-list

Question about insertion of doubly linked list in C


I'm trying to implement doubly linked list in C and running into some issue about head insertion.

LinkedListNode* CreateLinkedListNode(int data) {
    LinkedListNode* node = (LinkedListNode*) malloc(sizeof(LinkedListNode*));
    if (node == NULL) {
        printf("Fail to create a linked list node");
        exit(1);
    }
    node->prev = NULL;
    node->next = NULL;
    node->data = data;

    return node;
}

void InsertLinkedList(LinkedListPtr list, int new_value) {
    LinkedListNode* node =  CreateLinkedListNode(new_value);

    node->next = list->head;
    if (list->head != NULL) {
        printf("%d\n", node->data);
        list->head->prev = node;
        printf("%d\n", node->data);
    }

    if (isEmpty(list)) {
        list->tail = node;
    }

    list->head = node;
    list->num_elements++;
}

After list->head->prev = node in InsertLinkedList() is executed, the node's value has been changed to some random number.

Any ideas on this problem?


Solution

  • You have not included enough of the code to make your error reproducible, however, I can see at least one problem: in your first call to malloc (the one in CreateLinkedListNode) you pass the size of a pointer when it seems you should be passing the size of the object pointed to. What you want is:

    LinkedListNode* node = (LinkedListNode*)
        malloc(sizeof(LinkedListNode));
    

    (Note that there is no asterisk in the sizeof argument.)