Rant: Why do unsafe string functions still exist?

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.

Comments (7)

  1. Jeff Clark says:

    Just FYI. This was posted to the MSDN site a couple of weeks ago.


  2. Gregg Miskelly says:

    The industry is definately making progress on this front. But I think we are progressing too slowly. For instance, Microsoft spent a lot of time security reviewing Windows Server 2003. But we didn’t fix this. Why? It would be nearly free.

  3. Jerry Pisk says:

    You’re way too confident that using ‘n’ string function won’t cause a buffer overrun. If you get the buffer size wrong it will overrun no matter how much you believe that it won’t. And getting the buffer size wrong is trivial, at least to people who would buffer overrun in the first place – using sizeof() for Unicode strings, bad pointer arithmetics when adding strings, and so on…

  4. Gregg Miskelly says:

    First, use templates like above (SafeStrCopy), and you will never get the size wrong. You can use them anytime that your buffer is fixed size. If you have a dynamic buffer, use CString.

    Second, you are not going to get the size wrong 100% of the time, so you have still made an improvement.

  5. a little comment says:

    your web page looks screwy on mozilla, dude.

Skip to main content