1
votes

I have used the code given in this answer Netcdf Fortran array allocation at run time but I get a run time error when I run this code

forrtl : severe(151) allocatable array is already allocated

When I recompile with -g and -traceback the error is traced back to this line

allocate(lats(latlen))

Can memory be modified at runtime? I am using Fortran and the compiler is ifort.

Here is my code

  integer retval,reason,i,in_ndim,ierr
  integer ncid, lat_dimid,lat_varid, latlen
  integer lon_varid,lonlen
  character*(*) LAT_NAME, LON_NAME
  parameter (LAT_NAME='lat', LON_NAME='lon')
  real lats[allocatable](:)
  real lons[allocatable](:)

  call system('ls hgt_*.nc > hgtFiles.txt')

  open(10,file='hgtFiles.txt',action="read")
  varname = "hgt"
  do
     read(10,*,IOSTAT=reason) in_cfn
     if (reason/=0) EXIT
     print *,in_cfn
     retval = nf_open(in_cfn,NF_NOWRITE,ncid)
     if (retval .ne. nf_noerr) call handle_err(retval)

     retval = nf_inq_dimid(ncid,LAT_NAME,lat_dimid)
     if (retval .ne. nf_noerr) call handle_err(retval)

     retval = nf_inq_dimlen(ncid,lat_dimid,latlen)
     if (retval .ne. nf_noerr) call handle_err(retval)
     print *,latlen
     allocate(lats(latlen))
     retval = nf_inq_varid(ncid,LAT_NAME,lat_varid)
     if (retval .ne. nf_noerr) call handle_err(retval)
     retval = nf_get_var_real(ncid,lat_varid,lats)
     if (retval .ne. nf_noerr) call handle_err(retval)
    print *,lats
  end do
  close(10)
1

1 Answers

2
votes

You are allocating lats inside the loop. Therefore, at the second iteration it is already allocated and fails with the error you got. You basically have two options here:

  • If the dimensions do not change throughout the loop, pull the allocation outside
  • Or re-allocate your array inside the loop. In the simplest case, you need to put deallocate(lats) at the end of the loop body.