Ultimate
Ultimate

Reputation: 25

Run Time Error in insert at beginning (head) function in a Doubly Linked List in C?

Please point out the mistake in the logic of my code(if any). It is a function attempting to insert an element at the beginning of a Doubly Linked List in C language.

struct DLL *insertAthead(struct DLL *head, int newData)
{
    struct DLL *p = (struct DLL *)malloc(sizeof(struct DLL *));
    p->prev = NULL;
    p->next = head;
    head->prev = p;
    p->data = newData;
    head = p;
    return head;
}

Upvotes: 0

Views: 53

Answers (1)

Paul R
Paul R

Reputation: 212949

struct DLL *p = (struct DLL *)malloc(sizeof(struct DLL *));

should be:

struct DLL *p = malloc(sizeof(struct DLL));
                       ^^^^^^^^^^^^^^^^^^

Currently you are only allocating the size of a pointer (struct DLL *), rather than whatever size is needed for a struct DLL.

Note that some people prefer to write the above like this:

struct DLL *p = malloc(sizeof(*p));

which is arguably more robust.

Note that I've also removed the redundant cast, which is not a bug as such, but it's just unnecessary clutter and can in some cases be dangerous.

Upvotes: 1

Related Questions