Search code examples
winapiwindows-vistalocale

GetUserDefaultLocaleName() API is crashing


I have one application which reads user default locale in Windows Vista and above. When i tried calling the API for getting User default Locale API is crashing. Below is the code, It will be helpfull if any points the reason

#include <iostream>
#include <WinNls.h> 
#include <Windows.h>

int main()
{
    LPWSTR lpLocaleName=NULL;
    cout << "Calling GetUserDefaultLocaleName";
    int ret = GetUserDefaultLocaleName(lpLocaleName, LOCALE_NAME_MAX_LENGTH);
    cout << lpLocaleName<<endl;
}

Solution

  • In addition to the previous answers, you should also be aware that you can't print a wide string with cout; instead, you should use wcout. So:

    #include <iostream>
    #include <WinNls.h> 
    #include <Windows.h>
    
    #define ARRSIZE(arr) (sizeof(arr)/sizeof(*(arr)))
    
    using namespace std;
    
    int main()
    {
        WCHAR_T localeName[LOCALE_NAME_MAX_LENGTH]={0};
        cout<<"Calling GetUserDefaultLocaleName";
        int ret = GetUserDefaultLocaleName(localeName,ARRSIZE(localeName));
        if(ret==0)
            cout<<"Cannot retrieve the default locale name."<<endl;
        else
            wcout<<localeName<<endl;
        return 0;
    }