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

Jerry DeLisle <jvdelisle at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
     Ever confirmed|0                           |1
   Last reconfirmed|                            |2025-04-11
             Status|UNCONFIRMED                 |NEW

--- Comment #3 from Jerry DeLisle <jvdelisle at gcc dot gnu.org> ---
This simple patch avoids the segfault.

diff --git a/libgfortran/io/close.c b/libgfortran/io/close.c
index 81223113dc5..f57b618347c 100644
--- a/libgfortran/io/close.c
+++ b/libgfortran/io/close.c
@@ -84,6 +84,12 @@ st_close (st_parameter_close *clp)

   if (u != NULL)
     {
+      if (u->s == NULL)
+       {
+         if (u->unit_number < 0)
+           generate_error (&clp->common, LIBERROR_OS,
+                     "Unit number is negative with no associated file");
+       }
       if (close_share (u) < 0)
        generate_error (&clp->common, LIBERROR_OS, "Problem in CLOSE");
       if (u->flags.status == STATUS_SCRATCH)


As usual I started to explore a bit.

With this following variation we get our existing behaviour.

program foo
  integer :: iun = -1
  !open (iun)
  write(iun,*) "This is a test."
  close (iun)
end

gfc z1.f90 
$ ./a.out 
At line 4 of file z1.f90
Fortran runtime error: Unit number is negative and unit was not already opened
with OPEN(NEWUNIT=...)

This seems reasonable however when I remove the comment on the open statement
we dutifully create the file "fort.-1". This is also our existing behavior. In
my first attempt to generate an error on the open I run into a futex lock and
it hangs.

We can leave the open as is. However, I am wondering what is the right thing to
do.

I am curious what other compilers do with this.

program foo
  integer :: iun = -1
  open (iun)
  write(iun,*) "This is a test."
  close (iun)
end

Reply via email to