From 5e8427a8b53dfe5b9525626da2093eba8f9c8da9 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 13 Mar 2019 10:07:01 +0100 Subject: [PATCH] REDESIGNED: GetFileNameWithoutExt() Removed possible memory leak when using this function --- src/core.c | 48 ++++++++++++++++++------------------------------ 1 file changed, 18 insertions(+), 30 deletions(-) diff --git a/src/core.c b/src/core.c index 55b6ba82..c30c243d 100644 --- a/src/core.c +++ b/src/core.c @@ -180,15 +180,14 @@ //#define GLFW_EXPOSE_NATIVE_COCOA // WARNING: Fails due to type redefinition #include // Required for: glfwGetCocoaWindow() - #endif #endif #if defined(__linux__) - #include // for NAME_MAX and PATH_MAX defines - #define MAX_FILEPATH_LENGTH PATH_MAX // Use Linux define (4096) + #include // for NAME_MAX and PATH_MAX defines + #define MAX_FILEPATH_LENGTH PATH_MAX // Use Linux define (4096) #else - #define MAX_FILEPATH_LENGTH 256 // Use common value + #define MAX_FILEPATH_LENGTH 512 // Use common value #endif #if defined(PLATFORM_ANDROID) @@ -1676,37 +1675,26 @@ const char *GetFileName(const char *filePath) // Get filename string without extension (memory should be freed) const char *GetFileNameWithoutExt(const char *filePath) { - char *result, *lastDot, *lastSep; - - char nameDot = '.'; // Default filename to extension separator character - char pathSep = '/'; // Default filepath separator character - - // Error checks and allocate string - if (filePath == NULL) return NULL; - - // Try to allocate new string, same size as original - // NOTE: By default strlen() does not count the '\0' character - if ((result = (char *)malloc(strlen(filePath) + 1)) == NULL) return NULL; - - strcpy(result, filePath); // Make a copy of the string - - // NOTE: strrchr() returns a pointer to the last occurrence of character - lastDot = strrchr(result, nameDot); - lastSep = (pathSep == 0)? NULL : strrchr(result, pathSep); - - if (lastDot != NULL) // Check if it has an extension separator... + #define MAX_FILENAMEWITHOUTEXT_LENGTH 64 + + static char fileName[MAX_FILENAMEWITHOUTEXT_LENGTH]; + memset(fileName, 0, MAX_FILENAMEWITHOUTEXT_LENGTH); + + strcpy(fileName, GetFileName(filePath)); // Get filename with extension + + int len = strlen(fileName); + + for (int i = 0; (i < len) && (i < MAX_FILENAMEWITHOUTEXT_LENGTH); i++) { - if (lastSep != NULL) // ...and it's before the extenstion separator... + if (fileName[i] == '.') { - if (lastSep < lastDot) - { - *lastDot = '\0'; // ...then remove it - } + // NOTE: We break on first '.' found + fileName[i] = '\0'; + break; } - else *lastDot = '\0'; // Has extension separator with no path separator } - return result; // Return the modified string + return fileName; } // Get directory for a given fileName (with path)