Quote:
How is that possible sir! Second code is written by a renowned youtuber 'code_with_harry'.
I know. But here is renowed expert CPallini :-D. If you run Harry's code using Valgrind, then you get (something similar to)
==3144== LEAK SUMMARY:
==3144== definitely lost: 64 bytes in 4 blocks
==3144== indirectly lost: 0 bytes in 0 blocks
==3144== possibly lost: 0 bytes in 0 blocks
==3144== still reachable: 0 bytes in 0 blocks
==3144== suppressed: 0 bytes in 0 blocks
==3144==
==3144== For lists of detected and suppressed errors, rerun with: -s
==3144== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 0 from 0)
On the other hand, if you run the following, alternative code
#include
#include
struct Node
{
int val;
struct Node * next;
};
void traversal(const struct Node * p)
{
printf("------------\n");
while (p)
{
printf("%d ",p->val);
p = p->next;
}
printf("\n------------\n");
}
// isEmpty is not strictly needed
// isFull is meaning-less
struct Node * enqueue(struct Node *p, int val)
{
struct Node * prev = NULL;
while (p)
{
prev = p;
p = p->next;
}
p = malloc(sizeof(struct Node ));
if ( p )
{
p->val = val;
p->next = NULL;
if ( prev )
prev->next = p;
}
return p;
}
int dequeue(struct Node ** pp)
{
int val = -1;
struct Node * p = *pp;
if ( p )
{
val = p->val;
*pp = p->next;
free(p);
}
return val;
}
int main()
{
struct Node * ph = enqueue(NULL, 11);
enqueue(ph, 22);
enqueue(ph, 33);
enqueue(ph, 44);
traversal(ph);
dequeue(&ph);
dequeue(&ph);
traversal(ph);
dequeue(&ph);
dequeue(&ph);
return 0;
}
then Valgrind is somewhat happier:
==3153== HEAP SUMMARY:
==3153== in use at exit: 0 bytes in 0 blocks
==3153== total heap usage: 5 allocs, 5 frees, 1,088 bytes allocated
==3153==
==3153== All heap blocks were freed -- no leaks are possible
==3153==
==3153== For lists of detected and suppressed errors, rerun with: -s
==3153== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
"In testa che avete, Signor di Ceprano?" -- Rigoletto