问题
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