0

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;
}
Ultimate
  • 25
  • 2
  • 8

1 Answers1

1
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.

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • Could you please elaborate as to why did the pointer memory allocation statement(in my code) did not work. I have been using that statement format for quite a long time and it had never created a problem until this time. And why did removing the star from malloc(struct DLL *) solve the problem? – Ultimate Dec 27 '21 at 11:28
  • 1
    @Ultimate he told you in the answer. You only allocated pace for a pointer, you wanted the space for a struct DLL – Fredrik Dec 27 '21 at 11:39