Viewports: fixed a crash related to toggling visibility of different windows in a dock hierarchy. (#9631)

See test "viewport_owner_change_3"
diff --git a/docs/CHANGELOG.txt b/docs/CHANGELOG.txt
index 754b814..bb932d1 100644
--- a/docs/CHANGELOG.txt
+++ b/docs/CHANGELOG.txt
@@ -151,6 +151,8 @@
 - Viewports:
   - Fixed an issue where in some code paths, a newly created modal in its own
     viewport would be created with `ImGuiViewportFlags_NoFocusOnAppearing`.
+  - Fixed a crash related to toggling visibility of different windows in a dock
+    hierarchy hosted by a secondary viewport. (#9631) [@fabrisdnl, @ocornut]
 - Backends:
   - SDL2, SDL3: on macOS: fixed stuck down keys/buttons when they were held while thee
     focused viewport gets destroyed (Regression on macOS in 1.91.1) (#9121, #7853)
diff --git a/imgui.cpp b/imgui.cpp
index b420729..77a3859 100644
--- a/imgui.cpp
+++ b/imgui.cpp
@@ -17668,7 +17668,7 @@
             IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
         window->Viewport = window->ParentWindow->Viewport;
     }
-    else if (window->DockNode && window->DockNode->HostWindow)
+    else if (window->DockNode && window->DockNode->HostWindow && window->DockNode->HostWindow->Viewport)
     {
         // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
         window->Viewport = window->DockNode->HostWindow->Viewport;