From 10e46b2ffe798159e6c5d386bfc63364cd155b93 Mon Sep 17 00:00:00 2001
From: "Ryan C. Gordon" <[EMAIL REDACTED]>
Date: Wed, 4 Nov 2026 13:11:34 -0500
Subject: [PATCH] Mix_LoadWav_RW: more-careful realloc for optional buffer
shrink.
Since SDL2's `SDL_realloc(x, 0)` might free `x` and return `NULL`, we only
try to reallocate if the buffer is still > 0 bytes, to avoid an unexpected
double-free later.
And, since we're only doing this to shrink the buffer, don't bother
realloc'ing at all if the buffer is already as small as it can be.
SDL3_mixer rewrote most of this code (and SDL3's `SDL_realloc` never frees the
pointer if zero bytes are requested), so this is strictly an SDL2_mixer issue.
Fixes #911.
---
src/mixer.c | 17 ++++++++++-------
1 file changed, 10 insertions(+), 7 deletions(-)
diff --git a/src/mixer.c b/src/mixer.c
index 25bd6dec7..a4abe90a8 100644
--- a/src/mixer.c
+++ b/src/mixer.c
@@ -787,8 +787,8 @@ Mix_Chunk *Mix_LoadWAV_RW(SDL_RWops *src, int freesrc)
SDL_AudioSpec wavespec, *loaded;
SDL_AudioCVT wavecvt;
int samplesize;
+ int allocation_size = 0;
int wavfree; /* to decide how to free chunk->abuf. */
- Uint8 *resized_buf;
/* rcg06012001 Make sure src is valid */
if (!src) {
@@ -864,9 +864,10 @@ Mix_Chunk *Mix_LoadWAV_RW(SDL_RWops *src, int freesrc)
SDL_free(chunk);
return NULL;
}
+ allocation_size = wavecvt.len*wavecvt.len_mult;
samplesize = ((wavespec.format & 0xFF)/8)*wavespec.channels;
wavecvt.len = chunk->alen & ~(samplesize - 1);
- wavecvt.buf = (Uint8 *)SDL_calloc(1, wavecvt.len*wavecvt.len_mult);
+ wavecvt.buf = (Uint8 *)SDL_calloc(1, allocation_size);
if (wavecvt.buf == NULL) {
Mix_OutOfMemory();
if (wavfree) {
@@ -891,12 +892,14 @@ Mix_Chunk *Mix_LoadWAV_RW(SDL_RWops *src, int freesrc)
return NULL;
}
- resized_buf = SDL_realloc(wavecvt.buf, wavecvt.len_cvt);
- if (resized_buf == NULL) {
- chunk->abuf = wavecvt.buf;
- } else {
- chunk->abuf = resized_buf;
+ chunk->abuf = wavecvt.buf;
+ if ((wavecvt.len_cvt > 0) && (wavecvt.len_cvt < allocation_size)) { /* see if we can shrink this allocation. */
+ Uint8 *resized_buf = SDL_realloc(wavecvt.buf, wavecvt.len_cvt);
+ if (resized_buf != NULL) {
+ chunk->abuf = resized_buf;
+ }
}
+
chunk->alen = wavecvt.len_cvt;
wavfree = 0;
}