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;
}
CodePudding user response:
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.