BUG: ExpandEnvironmentStringsA Returns Wrong Byte Count

ID: Q234874


The information in this article applies to:


SYMPTOMS

ExpandEnvironmentStringsA, the ANSI version of ExpandEnvironmentStrings, returns twice the number of bytes that are in the string. For example, if the string is 10 characters long, ExpandEnvironmentStringsA returns 20. In fact, ExpandEnvironmentStringsA returns the Unicode byte count, not the ANSI byte count.


RESOLUTION

To work around this bug, you can determine the real length of the string by using lstrlenA(). Because ExpandEnvironmentStringsA returns a count that includes the trailing NULL, be sure to add 1 (one) to the count returned by lstrlenA().


STATUS

Microsoft has confirmed this to be a bug in the Microsoft products listed at the beginning of this article.


MORE INFORMATION

The following code demonstrates how to reproduce and detect this behavior:


#include <windows.h>
#include <stdio.h>

#define STR_LEN 40

void main (void)
{
   DWORD ansi_str_len,
         unicode_str_len;

   char psz_ansi_string[STR_LEN];
   WCHAR psz_unicode_string[STR_LEN];


   ansi_str_len = ExpandEnvironmentStringsA ("%systemroot%",
                                             psz_ansi_string, STR_LEN);

   unicode_str_len = ExpandEnvironmentStringsW (L"%systemroot%",
                                                psz_unicode_string,
                                                STR_LEN);

   /*
      ExpandEnvironmentStrings returns number of bytes for the string in
      ANSI (including terminating NULL), or number of characters for the
      string in Unicode (including terminating NULL).

      On Windows NT 4.0, the ANSI version of ExpandEnvironmentStrings 
      returns twice the number of bytes it should.
   */ 
   printf("ExpandEnvironmentStringsA (%s) returned %lu bytes\n",
          psz_ansi_string, ansi_str_len);
   printf("\t It should have returned %lu bytes\n",
          lstrlenA(psz_ansi_string)+1);

   wprintf(L"\nExpandEnvironmentStringsW (%s) returned %lu chars\n",
          psz_unicode_string, unicode_str_len);
   wprintf(L"\t It should have returned %lu chars\n",
           lstrlenW(psz_unicode_string)+1);
} 

Additional query words: environment variables expand


Keywords          : kbAPI kbKernBase kbSDKWin32 kbDSupport 
Version           : winnt:4.0
Platform          : winnt 
Issue type        : kbbug 

Last Reviewed: July 8, 1999