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:
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:
And cause a compiler error on these calls:
char* buff = new char;
In my experience, most call sites to strcpy look like the first example.