Memory leaks in standard code
FX
fxcoudert@gmail.com
Fri Feb 15 15:11:00 GMT 2008
> But I have to confess I'm a bit ignorant of what this patch is supposed
> to do, compared to say using valgrind or similar tools.
Well, you can't know what I'm doing when I didn't say :)
I've finished my patch. It's working by registering allocations and
deallocations at runtime (thus is a bit time-consuming) in a hash
table, and checking at the end of the program what we have leaked.
$ cat leak.f90
real, pointer :: a(:)
integer :: i
do i = 1, 3
allocate(a(5000))
nullify(a)
end do
end
$ gfortran leak.f90 -fruntime-check=memleaks
$ ./a.out
Fortran runtime checking: found 3 memory leaks
- at line 5 of file 'leak.f90', allocation of size 20000
- at line 5 of file 'leak.f90', allocation of size 20000
- at line 5 of file 'leak.f90', allocation of size 20000
Of course, the output can be made less repetitive, but I think the
basics are there. When memchecking is enabled, instead of calling
__builtin_malloc, the front-end emits calls like this one (from the
tree dump of leak.f90):
D.920 = _gfortran_malloc_check (20000, &"leak.f90"[1]{lb: 1 sz: 1}, 5, 0);
The library registers the allocation. Similarly, calls to free() are
changed into calls to _gfortran_free_check(), which removes the
corresponding allocation from the hash table. Finally, at then end of
MAIN__, the front-end emits a call to _gfortran_memory_check_report(),
which checks what allocations weren't deallocated and report.
Now, this seems to me quite useful (valgrind is not present on all
platforms, and is not Fortran-aware). It also can be extended to
report memory usage (peak memory, peak memory per procedure, location
of the largest allocations). But before I put more work into
beautifying it, I want to have input from others. I think it's a nice
new feature, helpful to users, and moreover, it's not a large or
intrusive patch:
The current front-end patch is 800 lines (in unified diff form; 100
lines removed, 200 lines added), including
- the a new handling of options (to allow for a generic
-fruntime-check=bounds,memleaks option),
- some code factoring of the memory allocation routines (which I
intend to do anyway), and
- changes to the driver to add -liberty at linking (required because
I use libiberty's hash tables in the library).
The library side is a single file (runtime/memory_checking.c), which
is 180 lines long. The complete current patch is attached to this
mail.
I'm looking forward to hearing your comments, ideas, likes and dislikes.
Thanks,
FX
--
FX Coudert
http://www.homepages.ucl.ac.uk/~uccafco/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: memleaks.diff
Type: application/octet-stream
Size: 39520 bytes
Desc: not available
URL: <http://gcc.gnu.org/pipermail/fortran/attachments/20080215/9bc62768/attachment.obj>
More information about the Fortran
mailing list