SDL: Addressed memory leak in SDL_coreaudio.m (a9da8)

From a9da8dd22d38d277e72d5793ac0c6303d085b694 Mon Sep 17 00:00:00 2001
From: obeecodes <[EMAIL REDACTED]>
Date: Sat, 15 Jun 2024 00:32:36 -0400
Subject: [PATCH] Addressed memory leak in SDL_coreaudio.m

(cherry picked from commit 3b5dce10c473ed16dfc36ab345955257c0676862)
---
 src/audio/coreaudio/SDL_coreaudio.m | 29 ++++++++++++++++++++++++++++-
 1 file changed, 28 insertions(+), 1 deletion(-)

diff --git a/src/audio/coreaudio/SDL_coreaudio.m b/src/audio/coreaudio/SDL_coreaudio.m
index 26da64d7edd3c..66a8c9efc6d68 100644
--- a/src/audio/coreaudio/SDL_coreaudio.m
+++ b/src/audio/coreaudio/SDL_coreaudio.m
@@ -806,7 +806,34 @@ static int assign_device_to_audioqueue(_THIS)
     result = AudioObjectGetPropertyData(this->hidden->deviceID, &prop, 0, NULL, &devuidsize, &devuid);
     CHECK_RESULT("AudioObjectGetPropertyData (kAudioDevicePropertyDeviceUID)");
     result = AudioQueueSetProperty(this->hidden->audioQueue, kAudioQueueProperty_CurrentDevice, &devuid, devuidsize);
-    CHECK_RESULT("AudioQueueSetProperty (kAudioQueueProperty_CurrentDevice)");
+
+    /*
+       If AudioObjectGetPropertyData succeeds and AudioQueueSetProperty fails,
+       calling CHECK_RESULT("AudioQueueSetProperty (kAudioQueueProperty_CurrentDevice)");
+       will cause a memory leak since it returns
+    */
+
+    // !!! FIXME: do we need to CFRelease(devuid)
+    /* Yes
+     CFStringRef is passed to AudioObjectGetPropertyData as an argument of type
+     UnsafeMutableRawPointer. As stated in the Apple Developer Documentation,
+     "The UnsafeMutableRawPointer type provides no automated memory management,
+     no type safety, and no alignment guarantees. You are responsible for
+     handling the life cycle of any memory you work with through
+     unsafe pointers, to avoid leaks or undefined behavior"
+    */
+
+    //This is the quickest fix
+    if (result != noErr) {
+        const char* msg = "AudioQueueSetProperty (kAudioQueueProperty_CurrentDevice)";
+        SDL_Log("COREAUDIO: Got error %d from '%s'!\n", (int)result, msg);
+        CFRelease(devuid);
+        SDL_SetError("CoreAudio error (%s): %d", msg, (int)result);
+        return 0;
+    }
+
+    //Release once you've finished using CFStringRef
+    CFRelease(devuid);
 
     return 1;
 }