One thing that I fail to understand is why, in 2004, we still have code that uses strcat, strcpy, sprintf or any of the other string functions that don’t take a buffer size input. Microsoft, Open source, etc all still use these functions. Why? Can you write safe code that uses these functions? Sure. Can you write unsafe code that uses the ‘n’ versions? Sure, but at least it won't buffer overrun. Why bother trying to figure out if a call site to strcpy is safe? Just replace it with StringCchCopy. It’s easy to do. Much easier then proving that the call sight is okay.

What I would like to see is:

  1. The functions removed from the static versions of the CRT
  2. Add a regkey to disable the functions in the dynamic CRTs
  3. As a requirement before we ship a service pack, or new product, every call site removed

Oh, and if you think it is too hard to replace all the calls to strcpy. You can do this:

template <int CCH>

inline HRESULT SafeStrCopy(char (&szBuffer)[CCH], const char *szStr)

{

      C_ASSERT(CCH > 0);

      return StringCchCopy(szBuffer, CCH, szStr);

}

 

#define strcpy SafeStrCopy

This will automatically convert these kinds of calls to be safe:

      char buff[255];

      strcpy(buff, UserString);

And cause a compiler error on these calls:

      char* buff = new char[255];

      strcpy(buff, UserString);

In my experience, most call sites to strcpy look like the first example.