当前位置: 动力学知识库 > 问答 > 编程问答 >

visual c++ - Access Violation Error when using wcscat_s to concatenate two wchar_t*

问题描述:

I am trying to concatenate one wchar[] to a wchar_t* using wcscat_s function. I keep getting Access Violation Error.

Here is the code

HANDLE hFindDll = FindFirstFile(dllDir,&findDllData);

wchar_t *path = L"C:\\Users\\andy\\Documents\\SampleProj\\";

rsize_t rsize = wcslen(path)+wcslen(findDllData.cFileName)+5;

wcscat_s(path,rsize,findDllData.cFileName);

Any suggestions where I am going wrong?

P.S If I use wchar_t path[] instead of wchar_t* path , I get a Corruption Warning in debug mode, but it executes without breaking the applicaiton when I click continue. In release mode, the error doesn't show at all.

regards,

andy

Update: Here is the entire code: what I want to achieve is to play a wave file from a resoure embedded in a dll...

int _tmain(int argc, _TCHAR* argv[])

{

WIN32_FIND_DATA findDllData;

HANDLE hFindDll;

LPCWSTR dllDir = L"C:\\Users\\andy\\Documents\\SampleProj\\*.dll";

HMODULE hICR;

HRSRC hRes;

hFindDll = FindFirstFile(dllDir,&findDllData);

if(hFindDll != INVALID_HANDLE_VALUE)

{

do

{

const wchar_t * path = L"C:\\Users\\andy\\Documents\\SampleProj\\";

rsize_t rsize = wcslen(path)+wcslen(findDllData.cFileName)+2;

wchar_t dst[1024];

wcscat_s(dst,1024,path); //--> this is where EXCEPTION occurs

wcscat_s(dst,1024,findDllData.cFileName);

hICR = LoadLibrary(dst);

hRes = FindResource(hICR, MAKEINTRESOURCE(200), _T("WAVE"));

if(hRes != NULL)

{

break;

}

}while(FindNextFile(hFindDll,&findDllData));

HGLOBAL hResLoad = LoadResource(hICR, hRes);

PlaySound(MAKEINTRESOURCE(200), hICR,SND_RESOURCE | SND_ASYNC);

}

return 0;

}

网友答案:

Your path is a pointer to a constant, immutable, read-only array. You cannot cat into it, because the *cat() functions want to write into the destination buffer, appending data at the end.

Instead, create a mutable recipient buffer:

const wchar_t * path = L"C:\\Users\\andy\\Documents\\SampleProj\\";

wchar_t dst[LARGE_NUMBER] = { 0 };  // ugh, very 1990

wcscat_s(dst, LARGE_NUMBER, path);
wcscat_s(dst, LARGE_NUMBER, findDllData.cFileName);

(Update: Apparently there's also a templated overload of this function that recognizes static arrays: wcscat_s(dst, path);. Neat.)

网友答案:

You're writing over the end of a constant memory string. Try malloc'ing a wchat_t* buffer of a rsize length and copying path path and then appending filename into it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: