Re: OT: Possible memory leak in an exercise of a C handbook
On 16 Dec 2024 17:21 +0100, from martellif67@gmail.com (Franco Martelli):
>> Put in something to count the number of calls to malloc() and free()
>> respectively. Don't forget calls outside of loops.
>
> There isn't calls to malloc() or free() outside loops. What do you mean?
>From a quick re-glance through your code...
if ( head == NULL )
{
==> head = last = (DIGIT *) malloc( sizeof ( DIGIT ) );
head->dgt = last->dgt = i;
head->next = head->prev = last->next = last->prev = NULL;
return;
}
/* Otherwise, find the last element in the list */
for (p = head; p->next != NULL; p = p->next)
; /* null statement */
==> p->next = (DIGIT *) malloc( sizeof ( DIGIT ) );
and
for ( const DIGIT *p = head; p->next != NULL; p = p->next )
if ( p->prev != NULL )
free( p->prev );
==> free( last );
certainly look to me like they're outside of loops.
--
Michael Kjörling
🔗 https://michael.kjorling.se
Reply to: