There are no Safe Functions – only Safe Programming

The Platform SDK includes a set of string manipulation functions defined in strsafe.h.   These functions were added during the Windows Security push.  The functions offer an alternative to the C run-time string functions which is more consistent, and less error-prone than the C standard functions.

But in order for the functions to actually be safe, they still must be used correctly.   Wrongly used these functions are as unsafe as the old C runtime functions.

In order to use the functions safely the following must be true:

  1. The first parameter is a pointer to a memory buffer,
  2. The second parameter is the size of the buffer in bytes if when the function name begins with StringCb.  The second parameter is the size of the buffer in chars if when function name begins with StringCch
  3. The return code of the function is checked for errors

So when I see something like:

   StringCbCopy(Foo, 2, “\\“);

It immediately raises a red flag for me.   Unless 2 happens to be the number of bytes in Foo, this is not a safe use of the function!   The second parameter here is not the number of bytes remaining in the buffer but rather the number of bytes needed from the second string.    Usually, code like this is the results of someone who just converted the code from strncpy to StringCbCopy without making the necessary changes to actually benefit from the new API. 

Now consider the following code:

   

char FileName[MAX_PATH];

StringCbCopy(FileName, MAX_PATH, DirectoryName);

Is this usage a safe use of the function?  

Only if you will never try to convert the file name and directory name to wide char.    Although for a char, count of chars and count of bytes have the same numeric value, in this case MAX_PATH is a count of chars so either of the following would be better: 

// Use Count of Chars

StringCChCopy(FileName, MAX_PATH, DirectoryName);

// Use a count of bytes

StringCbCopy(FileName, sizeof(FileName), DirectoryName);

Each of the String APIs supports an Ex version that has output parameters returning a pointer to the terminating null at the end of the target string, and the remaining chars/bytes in the buffer.  The Ex versions provide an alternative to doing the pointer arithmetic yourself which is error prone and dangerous.

Program safely.

[edited 8-13-04]