SDL: Fixed crash if all displays have been disconnected

From cb107bef58759468d715d919009bd2987954dade Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Mon, 1 Aug 2022 14:23:50 -0700
Subject: [PATCH] Fixed crash if all displays have been disconnected

Fixes https://github.com/libsdl-org/SDL/issues/5867
---
 src/video/windows/SDL_windowsevents.c | 34 +++++++++++++--------------
 1 file changed, 17 insertions(+), 17 deletions(-)

diff --git a/src/video/windows/SDL_windowsevents.c b/src/video/windows/SDL_windowsevents.c
index 4a1cfda89d3..d7f77f72091 100644
--- a/src/video/windows/SDL_windowsevents.c
+++ b/src/video/windows/SDL_windowsevents.c
@@ -623,24 +623,24 @@ WIN_KeyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam)
 
 static void WIN_CheckICMProfileChanged(SDL_Window* window)
 {
-    SDL_VideoDisplay* display = SDL_GetDisplayForWindow(window);
-    SDL_DisplayData* data = (SDL_DisplayData*)display->driverdata;
-    static WCHAR currentIcmFileName[MAX_PATH] = { '\0' };
-    WCHAR icmFileName[MAX_PATH];
-    HDC hdc;
-    SDL_bool succeeded;
-    DWORD fileNameSize = MAX_PATH;
-
-    hdc = CreateDCW(data->DeviceName, NULL, NULL, NULL);
-    if (hdc) {
-        succeeded = GetICMProfileW(hdc, &fileNameSize, icmFileName);
-        DeleteDC(hdc);
-        if (succeeded) {
-            
-            if (SDL_wcsncmp(currentIcmFileName, icmFileName, fileNameSize)) {
-                SDL_wcslcpy(currentIcmFileName, icmFileName, fileNameSize);
-                SDL_SendWindowEvent(window, SDL_WINDOWEVENT_ICCPROF_CHANGED, 0, 0);
+    SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
+    SDL_DisplayData *data = display ? (SDL_DisplayData*)display->driverdata : NULL;
+
+    if (data) {
+        HDC hdc = CreateDCW(data->DeviceName, NULL, NULL, NULL);
+        if (hdc) {
+            static WCHAR currentIcmFileName[MAX_PATH];
+            WCHAR icmFileName[MAX_PATH];
+            DWORD fileNameSize = SDL_arraysize(icmFileName);
+            if (GetICMProfileW(hdc, &fileNameSize, icmFileName)) {
+                /* fileNameSize includes '\0' on return */
+                fileNameSize *= sizeof(icmFileName[0]);
+                if (SDL_memcmp(currentIcmFileName, icmFileName, fileNameSize) != 0) {
+                    SDL_memcpy(currentIcmFileName, icmFileName, fileNameSize);
+                    SDL_SendWindowEvent(window, SDL_WINDOWEVENT_ICCPROF_CHANGED, 0, 0);
+                }
             }
+            DeleteDC(hdc);
         }
     }
 }