wcscat_s problem

混江龙づ霸主 提交于 2020-01-06 11:55:46

问题


Hi people i am currently working at my second visual studio made project :) . I am a delphi coder so please excuse my ignorance.

I want to write a simple routine to list some files and i wanted to write a simple function like Delphi's

IncludeTrailingPathDelimiter()

It's a simple function witch adds a \ to a file path if is not there...

So i came up with this

void listfiles(wchar_t * root)
{

    if (root[wcslen(root) - 1] != L'\\') 
        wcscat_s(root,wcslen(root)+2,L"\\");

    printf("%S",root);

}

It works but after exiting the function i get an (Stack Corruption) over this line

wcscat_s(root,wcslen(root)+2,L"\\"); 

What am i doing wrong do i need to allocate memory to the new created buffer or what?


回答1:


Using the safe string functions is fine, but you do need to use them properly. The 2nd argument to wcscat_s() is the size of the buffer. You don't know the size of the buffer in this code, it most certainly isn't wcslen(root)+2. Rewrite the function like this:

void listfiles(wchar_t * root, size_t rootSize)
{
    if (root[wcslen(root) - 1] != L'\\') 
        wcscat_s(root, rootSize, L"\\");

    printf("%S",root);
}

...
wchar_t buffer[666];
...
listfile(buffer, sizeof(buffer) / sizeof(buffer[0]));

And now the debugger will step in when your buffer is too small. It is.



来源:https://stackoverflow.com/questions/7123157/wcscat-s-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!