I found a function that deletes the head node of a Linked List and shifts the head to the next node. What is the use of assigning head to p, and after shifting head, de-allocating it, if one could just shift head and get the same result.
I just used printf("%d", head->data) and head = head->next, and got the same result. Am I wasting any memory?
// Why should I use this :
void deleteFromFront() {
node p = head;
printf("\n\tThe deleted element is : %d\n", head->data);
head = head->next;
free(p);
}
// And not this :
void deleteFromFront() {
printf("\n\tThe deleted element is : %d\n", head->data);
head = head->next;
}
This version:
node p = head;
printf("\n\tThe deleted element is : %d\n", head->data);
head = head->next;
free(p);
free the old head node, and this version:
printf("\n\tThe deleted element is : %d\n", head->data);
head = head->next;
does not. The first version must be used if you want to free the old head node. If you free
a piece of memory, it can be reused the next time you call malloc
. If you don't free
your memory when you're done with it, your program will use more and more memory because the system still thinks your program is using it. This is called a memory leak.