EXA01-F. Do not read uninitialized memory
Reading variables before they are defined results in undefined behavior. This rule applies to all data entities, including scalars, arrays, derived types, pointers, and allocatable variables. Accessing undefined data compromises program state integrity and may lead to incorrect computations, non-deterministic results, or crashes.
Compilers are not required to warn about uninitialized variables, and even when warnings are generated, the code may still compile and execute. Some compilers provide options to automatically initialize variables (for example, -finit-integer=0 in gfortran), but relying on these features is risky: it hides logical errors and reduces portability across different compilers and platforms.
Noncompliant Code Example
The following program attempts to sum the elements of an array. The variable sum is not explicitly initialized. Its initial value is indeterminate, so the result of sum_array is undefined and may vary depending on the compiler or runtime environment.
! example_array.f90
program main
use iso_fortran_env, only: real32
implicit none
real(kind=real32) :: array(5)
array = [0.24, 0.33, 0.17, 0.89, 0.05]
print *, "Sum is:", sum_array(array)
contains
pure real(kind=real32) function sum_array(array)
implicit none
real(kind=real32), intent(in) :: array(:)
real(kind=real32) :: sum
integer :: i
do i = 1, size(array, 1)
sum = sum + array(i)
end do
sum_array = sum
end function sum_array
end program main
Compliant Solution
The solution is straightforward: always initialize variables before use.
real(kind=real32) :: sum
sum = 0
This principle applies to all variable types, including other elemental types like integer derived types and arrays.
For dynamic arrays, Fortran provides pointer and allocatable types. Allocatable arrays are safer because they start unallocated and automatically manage memory, reducing the risk of reading uninitialized memory.
Risk Assessment
Reading uninitialized variables is undefined behavior. It can produce incorrect results, crashes, or security vulnerabilities, including the potential execution of arbitrary code.
Always explicitly initialize variables before reading or using them. Do not rely on compiler-specific default initialization or flags. For arrays and dynamic data, prefer allocatable over pointer when possible, ensure proper allocation and initialization.
| Rule | Severity | Likelihood | Detectable | Repairable | Priority | Level |
| EXA01-F | High | Likely | Yes | Yes | P27 | L1 |
Attachments:
button_arrow_left.png (image/png)
button_arrow_up.png (image/png)
button_arrow_right.png (image/png)


