MSC03-F. Do not depend on undefined behavior
Undefined behavior refers to the execution of a nonconforming 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
In this noncompliant example, a code attempts to detect integer overflow by checking whether the condition a + 100 > a is true or false. Apparently, this condition must always be true. However, 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. As a result the code may be miscompiled or behave unpredictably when optimizations are enabled.
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 (.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
In the compliant solution, the code does not depend on undefined behavior:
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 across compilers or platforms. Programmers should ensure that the code avoids undefined behavior in all cases.
| Rule | Severity | Likelihood | Detectable | Repairable | Priority | Level |
|---|---|---|---|---|---|---|
| MSC03-F | High | Likely | No | No | P9 | L2 |
Attachments:
button_arrow_left.png (image/png)
button_arrow_up.png (image/png)
button_arrow_right.png (image/png)


