From aac7d1c2ae928e82becf6e01988d4e3c32fafcf8 Mon Sep 17 00:00:00 2001 From: Sam Lantinga Date: Sat, 27 Jan 2024 12:15:43 -0800 Subject: [PATCH] Report out of memory instead of crashing in SDL_LoadFile_RW() Fixes https://github.com/libsdl-org/SDL/issues/8935 (cherry picked from commit 52975961326797558d1c66a02cb32870ff7be6d4) --- src/file/SDL_rwops.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/file/SDL_rwops.c b/src/file/SDL_rwops.c index 126807535e..a691a5ce07 100644 --- a/src/file/SDL_rwops.c +++ b/src/file/SDL_rwops.c @@ -718,12 +718,12 @@ void *SDL_LoadFile_RW(SDL_RWops *src, size_t *datasize, int freesrc) { static const Sint64 FILE_CHUNK_SIZE = 1024; Sint64 size; - size_t size_read, size_total; + size_t size_read, size_total = 0; void *data = NULL, *newdata; if (!src) { SDL_InvalidParamError("src"); - return NULL; + goto done; } size = SDL_RWsize(src); @@ -731,8 +731,11 @@ void *SDL_LoadFile_RW(SDL_RWops *src, size_t *datasize, int freesrc) size = FILE_CHUNK_SIZE; } data = SDL_malloc((size_t)(size + 1)); + if (!data) { + SDL_OutOfMemory(); + goto done; + } - size_total = 0; for (;;) { if ((((Sint64)size_total) + FILE_CHUNK_SIZE) > size) { size = (size_total + FILE_CHUNK_SIZE); @@ -753,12 +756,12 @@ void *SDL_LoadFile_RW(SDL_RWops *src, size_t *datasize, int freesrc) size_total += size_read; } - if (datasize) { - *datasize = size_total; - } ((char *)data)[size_total] = '\0'; done: + if (datasize) { + *datasize = size_total; + } if (freesrc && src) { SDL_RWclose(src); }