Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Optional argument segfault

Tim_Gallagher
New Contributor II
639 Views
Hi,

I found an interesting segfault that I'm hesitant to call a bug because I don't know what the standard has to say about it, but I think it should work.

Consider the following program:
[fortran]PROGRAM myTest
   IMPLICIT NONE

   INTEGER, POINTER :: scalarPtr
   INTEGER, DIMENSION(:), POINTER :: arrayPtr

   CALL SetScalar(scalarPtr)
   PRINT *, ASSOCIATED(scalarPtr)
   
   CALL SetArray(arrayPtr)
   PRINT *, ASSOCIATED(arrayPtr)

CONTAINS
   SUBROUTINE SetScalar(a,b)
      IMPLICIT NONE

      INTEGER, POINTER :: a
      INTEGER, INTENT(IN), TARGET, OPTIONAL :: b

      a => b
   END SUBROUTINE SetScalar
   
   SUBROUTINE SetArray(a,b)
      IMPLICIT NONE

      INTEGER, DIMENSION(:), POINTER :: a
      INTEGER, DIMENSION(:), INTENT(IN), TARGET, OPTIONAL :: b

      a => b
   END SUBROUTINE SetArray
END PROGRAM myTest[/fortran]
This is a simple example -- in our real case, it would be far too expensive to put IF(PRESENT()) around the arguments. We were hoping that if no argument is passed for the OPTIONAL dummy arguments, that the pointer would just point to NULL() and report back that it is not associated.

For scalars, this works correctly. However, for arrays, it segfaults. I'm sure it is because an array pointer is more than just a memory address as recently discussed here.

For what it's worth, this works as expected (both print statements are FALSE) for XLF, PGI, Cray, Pathscale, and Gfortran. But, I'm not sure what the standard says, so it may be a "feature" and not a "bug."

In the mean time, we just always pass in arrays for the array arguments to avoid the segfault.

Thoughts?

Tim
0 Kudos
1 Reply
mecej4
Honored Contributor III
639 Views
Article 12.4.1.6 of the F2003 standard says:

A dummy argument that is not optional shall be present. An optional dummy
31 argument that is not present is subject to the following restrictions:
32 (1) If it is a data object, it shall not be referenced or be defined.


Your code violates this on line-20 and line-29, if b is not present and is referenced. Therefore, your statements "works correctly" and "works as expected" are unsupported by the standard.
0 Kudos
Reply