chnging
chnging

Reputation: 775

A variable is being used without initialized

I am reading this http://www.winprog.org/tutorial/window_click.html and I am having trouble with the code. I am using VS 2012 and instead of char* or const char* I have to use LPCWSTR or LPWSTR.

In this particular case the problem is in the switch

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam,
    LPARAM lParam)
{
    switch(msg)
    {
        case WM_LBUTTONDOWN:
        {
            LPWSTR szFileName;
            HINSTANCE hInstance = GetModuleHandle(NULL);

            GetModuleFileName(hInstance, szFileName, MAX_PATH);
            MessageBox(hwnd, szFileName, L"This program is:",
                MB_OK | MB_ICONINFORMATION);
        }
        break;
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
        PostQuitMessage(0);
    break;
    default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

I use LPWSTR instead of the char that is shown in the tutorial and I compile it but when I click on the window instead of showing the information window an error shows up :

The variable 'szFileName' is being used without being initialized.

As I understand it GetModuleFileName() should write the information in szFileName which is empty at beginning so I can't really understand what the problem is.

Upvotes: 0

Views: 972

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385325

From the documentation for GetModuleFileName():

lpFilename [out]

A pointer to a buffer that receives the fully qualified path of the module. If the length of the path is less than the size that the nSize parameter specifies, the function succeeds and the path is returned as a null-terminated string.

You are giving it a pointer, but it is a pointer into infinite chaos. You have not actually allocated a buffer.

Go ahead and do that now:

wchar_t szFileName[MAX_PATH];
GetModuleFileName(hInstance, szFileName, MAX_PATH);

Upvotes: 8

AndersK
AndersK

Reputation: 36092

You need to declare an array instead, LPWSTR is just a pointer

so change

LPWSTR szFileName;

to

wchar_t szFileName[MAX_PATH];

Upvotes: 2

Related Questions