开发者

wcscat_s problem

开发者 https://www.devze.com 2023-03-29 01:53 出处:网络
Hi people i am currently working at my second visual studio made project :) . I am a delphi coder so please excuse my ignorance.

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开发者_StackOverflow社区 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号