diff --git a/gdb/ui-file.h b/gdb/ui-file.h
index 6a1d3964335..b7d3aebda9a 100644
--- a/gdb/ui-file.h
+++ b/gdb/ui-file.h
@@ -420,7 +420,7 @@ class wrapped_file : public ui_file
   { m_stream->emit_style_escape (style); }
 
   int fd () const override
-  { return m_stream->fd (); }
+  { return m_stream == nullptr ? -1 : m_stream->fd (); }
 
   void puts_unfiltered (const char *str) override
   { m_stream->puts_unfiltered (str); }
diff --git a/gdb/ui.h b/gdb/ui.h
index 891660896ef..ef977470302 100644
--- a/gdb/ui.h
+++ b/gdb/ui.h
@@ -163,6 +163,10 @@ struct ui
     {
       return current_ui->*F;
     }
+    bool operator== (nullptr_t p) const
+    {
+      return current_ui->*F == nullptr;
+    }
   };
 
   /* A ui_file that simply forwards.  */
diff --git a/gdb/unittests/ui-file-selftests.c b/gdb/unittests/ui-file-selftests.c
index 69e48735001..b9c1aca3774 100644
--- a/gdb/unittests/ui-file-selftests.c
+++ b/gdb/unittests/ui-file-selftests.c
@@ -48,6 +48,20 @@ run_tests ()
   scoped_restore save_7 = make_scoped_restore (&sevenbit_strings, true);
   check_one ("more weird stuff: \xa5", '\\',
 	     "more weird stuff: \\245");
+
+  {
+    /* There's a bug that has the effect "*redirectable_stderr () == nullptr".
+       In that case, gdb_stderr is not nullptr, but the underlying pointer is
+       a nullptr.  Check that "gdb_stderr->fd ()" doesn't dereference the
+       underlying nullptr.
+       This allows us to check for a usable gdb_stderr using
+       "gdb_stderr != nullptr && gdb_stderr->fd () == -1", as we do in
+       sig_write.  */
+    scoped_restore restore_stderr
+      = make_scoped_restore (redirectable_stderr (), nullptr);
+    SELF_CHECK (gdb_stderr != nullptr);
+    SELF_CHECK (gdb_stderr->fd () == -1);
+  }
 }
 
 } /* namespace file*/
