We’ve got a bunch of legacy code, written in straight C (some of which is K&R!), which for many, many years has been compiled using Visual C 6.0 (circa 1998) on an XP machine. We realize this is unsustainable, and we’re trying to move it to a modern compiler. Political issues have said that the most recent compiler allowed is VC++ 2005.
When compiling the project, there are many warnings about the unsafe string manipulation functions used (sprintf()
, strcpy()
, etc). Reviewing some of these places shows that the code is indeed unsafe; it does not check for buffer overflows. The compiler warning recommends that we move to using sprintf_s()
, strcpy_s()
, etc. However, these are Microsoft-created (and proprietary) functions and aren’t available on (say) gcc (although we’re primarily a Windows shop we do have some clients on various flavors of *NIX)
How ought we to proceed? I don’t want to roll our own string libraries. I only want to go over the code once. I’d rather not switch to C++ if we can help it.
8
First note that those “safe” functions are only marginally safer than the functions they replace. Most of those “safe” functions take an extra parameter informing it of the size of the destination buffer (which they use to check for overflows) and they check that no null pointers are passed where they shouldn’t.
This can catch certain errors, but not all of them and you could make an error in passing the wrong buffer size.
If you don’t want to switch to the secure functions, or you can’t due to portability requirements, then I would advise the following path:
- Compile your code with Visual Studio with the deprecation warnings enabled
- For each string manipulation function that gets flagged, evaluate if there really is a possibility of a buffer overflow or null pointer being passed.
- Where potential problems lie, modify the surrounding code to ensure the error can’t occur.
- When you are sure that all string handling functions are used in a secure way as much as possible, you add to your Visual Studio a define
_CRT_SECURE_NO_WARNINGS
to suppress the deprecation warnings.
As the code has been used successfully for a large number of years, I suspect that there are few places with problematic uses of the string functions.
4