SystemStats::getEnvironmentVariable is unreliable

Hi, SystemStats::getEnvironmentVariable often fails to return environment variables on Windows. In a sequence like this:

String a = SystemStats::getEnvironmentVariable("A", "");
String b = SystemStats::getEnvironmentVariable("B", "");
String c = SystemStats::getEnvironmentVariable("C", "");

If variable A is not defined then b and c will also be empty even if variables B and C are defined.

DWORD len = GetEnvironmentVariableW (name.toWideCharPointer(), nullptr, 0);
    if (GetLastError() == ERROR_ENVVAR_NOT_FOUND)
        return String (defaultValue);

That’s wrong, since successful calls do not update the value returned by GetLastError().
According to MSDN you need to check if len is 0.

Thanks, I’ll get that sorted.

1 Like