Skip to content

Commit

Permalink
Replace strlen upper bound with checks for '\0'
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
giulianobelinassi committed Jun 26, 2024
1 parent d07e8da commit b4e1921
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
21 changes: 12 additions & 9 deletions common/wwstd.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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;
}
}

Expand Down
5 changes: 3 additions & 2 deletions redalert/session.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

Expand Down

0 comments on commit b4e1921

Please sign in to comment.