SDL: Make sure count is 0 in out of memory conditions

From c5f570b30b1ba2073593b153c365b3f2c36b2095 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Tue, 31 Jan 2023 10:04:51 -0800
Subject: [PATCH] Make sure count is 0 in out of memory conditions

This prevents a crash if the caller assumes that they can always dereference the returned pointer if there is a non-zero count.
---
 src/joystick/SDL_joystick.c | 12 ++++++++----
 src/sensor/SDL_sensor.c     | 12 ++++++++----
 2 files changed, 16 insertions(+), 8 deletions(-)

diff --git a/src/joystick/SDL_joystick.c b/src/joystick/SDL_joystick.c
index 3db3795ee760..ead7897a2648 100644
--- a/src/joystick/SDL_joystick.c
+++ b/src/joystick/SDL_joystick.c
@@ -361,12 +361,12 @@ SDL_JoystickID *SDL_GetJoysticks(int *count)
             total_joysticks += SDL_joystick_drivers[i]->GetCount();
         }
 
-        if (count) {
-            *count = total_joysticks;
-        }
-
         joysticks = (SDL_JoystickID *)SDL_malloc((total_joysticks + 1) * sizeof(*joysticks));
         if (joysticks) {
+            if (count) {
+                *count = total_joysticks;
+            }
+
             for (i = 0; i < SDL_arraysize(SDL_joystick_drivers); ++i) {
                 num_joysticks = SDL_joystick_drivers[i]->GetCount();
                 for (device_index = 0; device_index < num_joysticks; ++device_index) {
@@ -379,6 +379,10 @@ SDL_JoystickID *SDL_GetJoysticks(int *count)
             SDL_assert(joystick_index == total_joysticks);
             joysticks[joystick_index] = 0;
         } else {
+            if (count) {
+                *count = 0;
+            }
+
             SDL_OutOfMemory();
         }
     }
diff --git a/src/sensor/SDL_sensor.c b/src/sensor/SDL_sensor.c
index 253eebaeb2ba..d974b39c27a1 100644
--- a/src/sensor/SDL_sensor.c
+++ b/src/sensor/SDL_sensor.c
@@ -115,12 +115,12 @@ SDL_SensorID *SDL_GetSensors(int *count)
             total_sensors += SDL_sensor_drivers[i]->GetCount();
         }
 
-        if (count) {
-            *count = total_sensors;
-        }
-
         sensors = (SDL_SensorID *)SDL_malloc((total_sensors + 1) * sizeof(*sensors));
         if (sensors) {
+            if (count) {
+                *count = total_sensors;
+            }
+
             for (i = 0; i < SDL_arraysize(SDL_sensor_drivers); ++i) {
                 num_sensors = SDL_sensor_drivers[i]->GetCount();
                 for (device_index = 0; device_index < num_sensors; ++device_index) {
@@ -133,6 +133,10 @@ SDL_SensorID *SDL_GetSensors(int *count)
             SDL_assert(sensor_index == total_sensors);
             sensors[sensor_index] = 0;
         } else {
+            if (count) {
+                *count = 0;
+            }
+
             SDL_OutOfMemory();
         }
     }