Freeing memory



I've written a small example of a linked-list. This works fine as a
linked list but according to valgrind (linux) there is a memory leak.
Given that I only have a handle on the start of the list what is the
best was to properly deallocate memory?

Thanks,

Simon Geard

program example7

type l_entry
integer :: value = -1
type(l_entry), pointer :: next
end type l_entry

type(l_entry), pointer :: first, current
integer :: i

! Fill the list with odd numbers 1...9
allocate(current)
first => current
do i=1,9,2
current = l_entry(i,null())
allocate(current%next)
current => current%next
end do

! Step thought the list outputting as we go
current => first
do
if (.not. associated(current%next)) exit
print *,current%value
current => current%next
end do
deallocate(first)
end program example7

valgrind summary:
==16147==
==16147== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 19 from
2)
==16147== malloc/free: in use at exit: 40 bytes in 5 blocks.
==16147== malloc/free: 13 allocs, 8 frees, 5318 bytes allocated.
==16147== For counts of detected errors, rerun with: -v
==16147== searching for pointers to 5 not-freed blocks.
==16147== checked 118792 bytes.
==16147==
==16147== LEAK SUMMARY:
==16147== definitely lost: 32 bytes in 4 blocks.
==16147== possibly lost: 0 bytes in 0 blocks.
==16147== still reachable: 8 bytes in 1 blocks.
==16147== suppressed: 0 bytes in 0 blocks.

.



Relevant Pages

  • Re: realloc in function
    ... My note about memory leak is also very important for proper use of realloc. ... > Keep in mind that assigning realloc result to the same pointer may lead ... > Why would you read Microsoft news from anywhere other then the MS news ... > " MVPs earn their status by being nominated by peers and Microsoft ...
    (microsoft.public.vc.language)
  • Re: CList Concept
    ... pointer instead of a list of object. ... called automatically by the list class destructor. ... CObject myObject = new CObject; ... if I do it this way, will I get memory leak? ...
    (microsoft.public.windowsce.embedded.vc)
  • Why is this a memory leak? (Valgrind / Linux)
    ... I'm hunting down a memory leak reported by Valgrind. ... valgrind doesn't report any memory leaks. ...
    (comp.unix.programmer)
  • Re: question on malloc(0)
    ... the pointer returned by malloc, it's a memory leak regardless ... After the malloccall, ptr presumably ... points to some small allocated chunk of memory. ...
    (comp.lang.c)
  • Memory Leak Explanation
    ... that Valgrind identifies this program as having a memory leak. ... Linux Mag Code Sample 2003 May ... int main ...
    (alt.comp.lang.learn.c-cpp)