https://gcc.gnu.org/bugzilla/show_bug.cgi?id=126116

--- Comment #3 from Ichikawa Ryu <ryu.ichikawa323 at gmail dot com> ---
Thank you for the quick response!

I completely agree that passing an arbitrary negative unit (like a raw -10) is
invalid Fortran. However, please note that this underlying state corruption
also breaks perfectly valid Fortran code.

According to the Fortran 2018 standard (WG5 N2146, Section 12.5.7.1):
"Execution of a CLOSE statement specifying a unit that does not exist, exists
but is connected to a file that does not exist, or has no file connected to it,
is permitted and affects no file or unit."

Repeating CLOSE on a valid unit that was previously generated via NEWUNIT and
already closed should be a safe no-op under this rule. However, the internal
file I/O corruption violates this standard behavior.

Here is a valid example that unexpectedly crashes:

program check
    implicit none
    integer :: u
    character(50) :: chr

    ! 1. Correctly generate a negative unit via NEWUNIT
    open(file="test.txt", newunit=u) ! u gets -10
    close(u) ! u (-10) is now closed and free

    ! 2. Internal I/O corrupts the state of unit -10
    write(chr, *) "test"

    ! 3. Redundant CLOSE on the valid unit 'u'.
    ! This should be a safe no-op according to the standard, 
    ! but it triggers the runtime error/segfault!
    close(u)
end program

Therefore, the root cause is indeed that internal file I/O must be completely
isolated and must not leak or affect the internal unit registry at all. If we
only add a check to reject raw negative integers, this valid code will still
unexpectedly crash.

Reply via email to