How does strcpy_s work?

In DEBUG mode, MicroSoft APIs fill the buffer with 0xfd, so they can check for an overflow.

This function doesn't truncate the copied string, but raises an exception!

It's always a pain to specify the size of the dest buffer (use _countof rather than sizeof), mostly when you use a pointer!

I have more problems with those "_s" APIs than with the standards ones!!


MSDN Says "The strcpy_s function copies the contents in the address of strSource, including the terminating null character, to the location that's specified by strDestination. The destination string must be large enough to hold the source string and its terminating null character. The behavior of strcpy_s is undefined if the source and destination strings overlap."


This is actually how to get the size of a stack array at run time without decaying it to a pointer:

template<typename T, size_t N> 
size_t arrSize(T (&array)[N])  
{
  return N;
}

You send it as a template reference, and the template mechanism deduces the size. So, you can do something like

int myArray[10];
cout << arrSize(myArray); // will display 10

So my guess is that this is how the "safe" MS strcpy_s is checking the sizes. Otherwise, if you pass just a pointer, there is NO STANDARD-COMPLIANT way of getting the size.

Tags:

C

String

Strcpy