Commit 9706feacaedff9f14b7ca8fde26db5340075c778

Sam Lantinga 2021-10-01T15:11:25

Update length after shortening string (thanks mayraud705!) Closes https://github.com/libsdl-org/SDL/pull/4698

diff --git a/src/joystick/SDL_joystick.c b/src/joystick/SDL_joystick.c
index 04c99b9..5c8f6e1 100644
--- a/src/joystick/SDL_joystick.c
+++ b/src/joystick/SDL_joystick.c
@@ -1757,8 +1757,13 @@ SDL_CreateJoystickName(Uint16 vendor, Uint16 product, const char *vendor_name, c
         size_t prefixlen = SDL_strlen(replacements[i].prefix);
         if (SDL_strncasecmp(name, replacements[i].prefix, prefixlen) == 0) {
             size_t replacementlen = SDL_strlen(replacements[i].replacement);
-            SDL_memcpy(name, replacements[i].replacement, replacementlen);
-            SDL_memmove(name+replacementlen, name+prefixlen, (len-prefixlen+1));
+            if (replacementlen <= prefixlen) {
+                SDL_memcpy(name, replacements[i].replacement, replacementlen);
+                SDL_memmove(name+replacementlen, name+prefixlen, (len-prefixlen)+1);
+                len -= (prefixlen - replacementlen);
+            } else {
+                /* FIXME: Need to handle the expand case by reallocating the string */
+            }
             break;
         }
     }
@@ -1768,11 +1773,9 @@ SDL_CreateJoystickName(Uint16 vendor, Uint16 product, const char *vendor_name, c
         int matchlen = PrefixMatch(name, &name[i]);
         if (matchlen > 0 && name[matchlen-1] == ' ') {
             SDL_memmove(name, name+matchlen, len-matchlen+1);
-            len -= matchlen;
             break;
         } else if (matchlen > 0 && name[matchlen] == ' ') {
             SDL_memmove(name, name+matchlen+1, len-matchlen);
-            len -= (matchlen + 1);
             break;
         }
     }