From b4e1921916a3db8fe5053d89b7a4189a40ccc3d7 Mon Sep 17 00:00:00 2001 From: Giuliano Belinassi Date: Wed, 26 Jun 2024 00:17:11 -0300 Subject: [PATCH] Replace strlen upper bound with checks for '\0' MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Strings in C are always terminated by the '\0' character. We can explore this to avoid sweeping through the string twice. Constructs like `for (i = 0; i < strlen(str); i++)` are even worse, as it will call strlen **for each character of the string**, which is O(n²) instead of O(n). Replace those cases as well. Signed-off-by: Giuliano Belinassi --- common/wwstd.h | 21 ++++++++++++--------- redalert/session.cpp | 5 +++-- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/common/wwstd.h b/common/wwstd.h index ab99bcc1..03c7d170 100644 --- a/common/wwstd.h +++ b/common/wwstd.h @@ -250,18 +250,22 @@ inline static void _splitpath(const char* path, char* drive, char* dir, char* fn return; } - for (int i = 0; i < strlen(path); i++) { - if (path[i] == '.') { - strcpy(ext, path + i + 1); + while (*path != '\0') { + if (*path == '.') { + strcpy(ext, path + 1); break; } + + ++path; } } inline static char* strupr(char* str) { - for (int i = 0; i < strlen(str); i++) - str[i] = toupper(str[i]); + while (*str != '\0') { + *str = toupper(*str); + ++str; + } return str; } @@ -278,10 +282,9 @@ inline static void strrev(char* str) inline static void _strlwr(char* str) { - int len = strlen(str); - - for (int i = 0; i < len; i++) { - str[i] = tolower(str[i]); + while (*str != '\0') { + *str = tolower(*str); + ++str; } } diff --git a/redalert/session.cpp b/redalert/session.cpp index 3a575f86..5057ca55 100644 --- a/redalert/session.cpp +++ b/redalert/session.cpp @@ -1089,8 +1089,9 @@ uint32_t SessionClass::Compute_Unique_ID(void) //------------------------------------------------------------------------ path = getenv("PATH"); if (path) { - for (i = 0; i < strlen(path); i++) { - Add_CRC(&id, (unsigned int)path[i]); + while (*path != '\0') { + Add_CRC(&id, (unsigned int)(*path)); + ++path; } }