Skip to main content
GitHub

MSC03-F. Do not depend on undefined behavior

Undefined behavior refers to the execution of a non-conforming Fortran program, in which language rules are violated due to erroneous constructs or invalid use of data. When a program exhibits undefined behavior, a Fortran compiler is free to produce any result: correct output, incorrect output, crashes, silent data corruption, or behavior that varies between optimization levels or platforms.

Noncompliant Code Example

A program that relies on integer overflow to detect errors is therefore nonconforming and may be miscompiled or behave unpredictably when optimizations are enabled.

The following nonconforming Fortran code attempts to detect integer overflow by checking whether a + 100 > a , which must always be true. It can evaluate to false if signed integer overflow occurs.

A conforming compiler is allowed to assume that overflow never happens, and as a consequence, the compiler may: remove the test entirely, reorder computations, or produce unexpected results.

Non-compliant code
program koo
  use iso_fortran_env, only : int32
  implicit none

  call foo(100_int32)
  call foo(huge(0_int32))

contains

  subroutine foo(a)
    integer(int32), intent(in) :: a
    integer(int32) :: tmp

    ! Attempt to detect overflow
    if (.not. (a + 100_int32 > a)) then
      error stop "Integer overflow detected"
    end if

    tmp = a + 100_int32
    print *, tmp, a
  end subroutine foo

end program koo

Compliant Solution

This compliant solution does not depend on undefined behavior:

Compliant code
program koo
  use iso_fortran_env, only : int32
  implicit none

  call foo(100_int32)
  call foo(huge(0_int32))

contains

  subroutine foo(a)
    integer(int32), intent(in) :: a
    integer(int32) :: tmp

    if (a > huge(a) - 100_int32) then
      error stop "Overflow would occur"
    end if

    tmp = a + 100_int32
    print *, tmp, a
  end subroutine foo

end program koo

Risk Assessment

Undefined behavior can produce incorrect results, silent data corruption, crashes, or nondeterministic behavior that varies with compiler or platform. Programmers should ensure that the code avoids undefined behavior in all cases.

RecommendationSeverityLikelihoodDetectableRepairablePriorityLevel
MSC03-FHighLikelyNoNoP9L2

Attachments: