Beginner
Beginner

Reputation: 59

wcscat_s String is not null terminated

I want to get all file name user selected. The format of return string is like: The folder user selected | filename1 | filename2 ......

Here is my code for creating multi-select dialog, get selected file names, and copy them to buffer variable. File names are seperated by "|"

HWND hDlg = NULL;
wchar_t* buffer = new wchar_t[32768];
void ShowDialog()
{
    OPENFILENAME ofn;
    wchar_t szFile[32768];
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = hDlg;
    ofn.lpstrFile = (wchar_t*)szFile;
    ofn.lpstrFile[0] = '\0';
    ofn.nMaxFile = sizeof(szFile);
    ofn.lpstrFileTitle = NULL;
    ofn.nMaxFileTitle = 0;
    ofn.lpstrInitialDir = NULL;
    ofn.Flags =  OFN_ALLOWMULTISELECT | OFN_ENABLESIZING | OFN_EXPLORER;
    if(GetOpenFileName(&ofn) == TRUE)
    {
        if(szFile[ofn.nFileOffset-1] != '\0')
        {
            wcscpy_s(buffer,sizeof(szFile),szFile);
        }
        else
        {
           //Multi-select
           wchar_t* p= szFile;
           int i =0;
           while(*p)
           {
                wchar_t* temp = new wchar_t[1024];
                //Copy p into temp
                wcscpy_s(temp,1024,p);
                if(i==0)
                {
                    //copy folder name into buffer
                    wcscpy_s(buffer,1024,temp);
                }
                else
                {
                   //cat file name with buffer
                   wcscat_s(buffer,1024,temp);
                }
                //seperated folder name and files name with "|"
                wcscat_s(buffer,2,L"|\0");
                i++;
                p += lstrlen(p) + 1;
            }
        }
    }
}

When i debug this code, run time error : "String is not null terminated" is appeared in line code : wscat_s(buffer,2,L"|\0");

Could you explain for me why and how to fix it.

Thanks for you helping

Upvotes: 0

Views: 3162

Answers (1)

mike.dld
mike.dld

Reputation: 3049

wcscat_s accepts buffer size as second argument, not the size of sequence being appended, so it should be:

wcscat_s(buffer, 32768, L"|");

instead. You're getting this error because certainly none of the first two characters in your buffer are '\0' at that point.

Upvotes: 2

Related Questions