EnvironGetenv: use strncmp instead of strlen and memcmp (dotnet/coreclr#27632)
authorBond-009 <bond.009@outlook.com>
Sat, 2 Nov 2019 17:13:47 +0000 (18:13 +0100)
committerJan Kotas <jkotas@microsoft.com>
Sat, 2 Nov 2019 17:13:47 +0000 (10:13 -0700)
Instead of iterating twice over the string, first for searching the
null-terminator and then to compare it to `name`, we only iterate
over it once.

Commit migrated from https://github.com/dotnet/coreclr/commit/d606bff508cf57477b21ebbe8c8a2f6494feed7e

src/coreclr/src/pal/src/misc/environ.cpp

index d00236e9803276f9251b695d6b044254ae9641a6..f2538752f6456d1bb9b8547cb536af135fe3a12e 100644 (file)
@@ -927,12 +927,7 @@ char* EnvironGetenv(const char* name, BOOL copyValue)
     size_t nameLength = strlen(name);
     for (int i = 0; palEnvironment[i] != nullptr; ++i)
     {
-        if (strlen(palEnvironment[i]) < nameLength)
-        {
-            continue;
-        }
-
-        if (memcmp(palEnvironment[i], name, nameLength) == 0)
+        if (strncmp(palEnvironment[i], name, nameLength) == 0)
         {
             char *equalsSignPosition = palEnvironment[i] + nameLength;