Santhosha
Santhosha

Reputation: 431

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;
}

Upvotes: 2

Views: 4236

Answers (3)

Matteo Italia
Matteo Italia

Reputation: 126927

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;
}

Upvotes: 2

t0mm13b
t0mm13b

Reputation: 34592

You need to have lpLocaleName initialized to a buffer prior to calling the API. As a general consensus, if an API has a LPWSTR data type parameter, call malloc or new on it first, to the desired length, in this case, LOCALE_NAME_MAX_LENGTH. Setting it to NULL and passing it to the API function is a guaranteed way to crash!

Hope this helps, Best regards, Tom.

Upvotes: 4

Nanook
Nanook

Reputation: 3322

I believe you need to initialise lpLocaleName to an empty string of 256 chars (for example) then pass the length (256) where you have LOCALE_NAME_MAX_LENGTH

Upvotes: 1

Related Questions