Problem with MPI Fortran code

I’ve been working with this MPI FORTRAN code for over a week. This code generates OUTPUT files but not NUM_OUT. I’m a beginner in programming and I’m trying to understand what the error is. I believe the MPI implementation is correct.

You allocated UPS twice, and tried to access it out-of-bounds afterwards!

78  ALLOCATE(UPS(istart-2:iend+2, 1:2))
:
117 ALLOCATE(UPS(ISTART:IEND, 1))
:
131     UPS(IEND + 1, 1) = CMPLX(DATA_BR, DATA_BI, KIND=8)
137     UPS(ISTART - 1, 1) = CMPLX(DATA_BR, DATA_BI, KIND=8)
143     UPS(IEND + 1, 1) = CMPLX(DATA_CR, DATA_CI, KIND=8)
162     UPS(I, 2) = UPS(I, 1) - ((U * DT / DX) * (UPS(I, 1) - UPS(I - 1, 1)))
175   UPS(POINTS - 1, 2) = UPS(POINTS - 1, 1) - ((U * DT / DX) * (UPS(POINTS - 1, 1) - UPS(POINTS - 2, 1)))
193 UPS(ISTART:IEND, 1) = UPS(ISTART:IEND, 2)

I’m surprised the compiler didn’t catch this.

For the problematic output file, since IEND is calculated,

69   IEND = MIN((MY_RANK + 1) * PARTS, POINTS)

It might be helpful to print out ISTART and IEND for each MPI rank, to ensure that IEND is always bigger that ISTART,

PRINT *, "Rank ", MY_RANK, " ISTART=", ISTART, " IEND=", IEND

Otherwise, this loop won’t execute at all.

209 DO I = ISTART-1, IEND+1
210   WRITE(40, *) X(I), UPS(I, 1)
211 END DO

Also, a minor suggestion: instead of using a separate internal write for PROC3,

108   WRITE(PROC3, FMT='(I10)') MY_RANK
109 OUTFILE = "OUTPUT_LFS" // TRIM(ADJUSTL(PROC3)) // ".dat"
:
205 WRITE(PROC3, FMT='(I10)') MY_RANK
206 OUTFILE = "NUM_OUT_" // TRIM(ADJUSTL(PROC3)) // ".dat"

why not write it directly to OUTFILE?

WRITE(OUTFILE, '("OUTPUT_LFS", I0, ".dat")') MY_RANK
WRITE(OUTFILE, '("NUM_OUT_", I0, ".dat")') MY_RANK

Finally, while some compilers may be smart enough to automatically deallocate memory on ALLOCATABLE variables once it’s out of scope, it’s good practice to manually clean up after yourself so you don’t accidentally introduce memory leaks.

1 Like

Allocatable arrays are always deallocated automatically at the end of scope though. So manually deallocating is probably not required.

3 Likes

@aerosayan There are certain edge cases tho, like with module variables and when using SAVE. In-depth discussion here:

1 Like