Gfortran -fanalyzer option

Gcc has an -fanalyzer option for static analysis, (added by a developer at Red Hat in 2020) as does gfortran. Does anyone use if for Fortran code or for C code? I tried it on one of my Fortran source files (5600 lines), and it slowed the compilation dramatically, from 1.3s without to 54s with the -fanalyzer option. The documentation does say “This analysis is much more expensive than other GCC warnings.” Gfortran -c -fanalyzer statistics.f90 said

statistics.f90:338:0:

  338 | if (size(ix) /= size(xx)) return
      | 
Warning: leak of 'istat.0_92' [CWE-401] [-Wanalyzer-malloc-leak]
  'stat_categories_many_str': events 1-3
    |
    |  344 | function stat_categories_many_str(cstat,ncat,ix,xx) result(yy)
    |      | 
    |......
    |  350 | yy = stat_categories_many(istat_str(cstat),ncat,ix,xx)
    |      | 
    |
    +--> 'stat_categories_many': events 4-7
           |
           |  330 | function stat_categories_many(istat,ncat,ix,xx) result(yy)
           |      | 
           |......
           |  338 | if (size(ix) /= size(xx)) return
           |      | 
           |

for the subroutine

function stat_categories_many(istat,ncat,ix,xx) result(yy)
integer      , intent(in) :: istat(:)
integer      , intent(in) :: ncat
integer      , intent(in) :: ix(:)
real(kind=dp), intent(in) :: xx(:)
real(kind=dp)             :: yy(size(istat),ncat)
integer                   :: i
yy    = 0.0_dp
if (size(ix) /= size(xx)) return
do i=1,ncat
   yy(:,i) = stat_vec_int_many(istat,pack(xx,ix==i))
end do
end function stat_categories_many

I don’t see anything wrong with the code.

1 Like

For the code

implicit none
integer, pointer :: ivec(:)
allocate(ivec(2))
ivec = [3,5]
print*,"ivec=",ivec
! deallocate(ivec)
end

the -fanalyzer option does say something useful:

c:\fortran\test>gfortran -fanalyzer -Wall -Wextra pointer.f90
pointer.f90:7:0:

    7 | end
      | 
Warning: leak of 'ivec.data' [CWE-401] [-Wanalyzer-malloc-leak]
  'main': events 1-2
    |
    |
    +--> 'MAIN__': events 3-14
           |
           |    1 | implicit none
           |      | 
           |    2 | integer, pointer :: ivec(:)
           |    3 | allocate(ivec(2))
           |      | 
           |    4 | ivec = [3,5]
           |      | 
           |    5 | print*,"ivec=",ivec
           |      | 
           |    6 | ! deallocate(ivec)
           |    7 | end
           |      | 
           |

with the -Wall -Wextra options alone, gfortran does not warn about the pointer not being deallocated. I believe such deallocations are recommended before the end of a program.

O, I did not know of that option - interesting! Like I wrote in another thread, I am collecting small programs that can demonstrate the capabilities of compilers to perform such analyses. The compile time is a trifle bothersome, but then having to dig up an error deep in the code is bothersome too.