From d9c10ed2646eea784ba71ae24ef53f67a497fc08 Mon Sep 17 00:00:00 2001 From: Asdqwe Date: Wed, 2 Oct 2024 05:49:06 -0300 Subject: [PATCH] Fixes GetClipboardText() memory leak for PLATFORM_DESKTOP_SDL (#4354) --- src/platforms/rcore_desktop_sdl.c | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/platforms/rcore_desktop_sdl.c b/src/platforms/rcore_desktop_sdl.c index 794f9e6a..90372c2f 100644 --- a/src/platforms/rcore_desktop_sdl.c +++ b/src/platforms/rcore_desktop_sdl.c @@ -57,6 +57,13 @@ #include "SDL_opengl.h" // SDL OpenGL functionality (if required, instead of internal renderer) #endif +//---------------------------------------------------------------------------------- +// Defines and Macros +//---------------------------------------------------------------------------------- +#ifndef MAX_CLIPBOARD_BUFFER_LENGTH + #define MAX_CLIPBOARD_BUFFER_LENGTH 1024 // Size of the clipboard buffer used on GetClipboardText() +#endif + //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- @@ -852,10 +859,22 @@ void SetClipboardText(const char *text) } // Get clipboard text content -// NOTE: returned string must be freed with SDL_free() const char *GetClipboardText(void) { - return SDL_GetClipboardText(); + static char buffer[MAX_CLIPBOARD_BUFFER_LENGTH] = { 0 }; + + char *clipboard = SDL_GetClipboardText(); + + int clipboardSize = snprintf(buffer, sizeof(buffer), "%s", clipboard); + if (clipboardSize >= MAX_CLIPBOARD_BUFFER_LENGTH) + { + char *truncate = buffer + MAX_CLIPBOARD_BUFFER_LENGTH - 4; + sprintf(truncate, "..."); + } + + SDL_free(clipboard); + + return buffer; } // Show mouse cursor @@ -1589,8 +1608,8 @@ int InitPlatform(void) // Initialize storage system //---------------------------------------------------------------------------- // Define base path for storage - CORE.Storage.basePath = SDL_GetBasePath(); // Alternative: GetWorkingDirectory(); - CHDIR(CORE.Storage.basePath); + CORE.Storage.basePath = SDL_GetBasePath(); // Alternative: GetWorkingDirectory(); + CHDIR(CORE.Storage.basePath); //---------------------------------------------------------------------------- TRACELOG(LOG_INFO, "PLATFORM: DESKTOP (SDL): Initialized successfully");