Preventing Buffer Overruns

Preventing buffer overruns is a matter of writing a robust application. For an excellent resource, see Writing Solid Code by Steve Maguire (Microsoft Press, 1993).

The most important step you can take to prevent buffer overruns is to always validate all your inputs. Likewise, nothing about the internal implementation of the function, nothing other than the expected input and output of the function, should be accessible outside the function.

Safe String Handling

String handling is the single largest source of buffer overruns. Although problems with the single-byte versions are discussed in this section, the same problems apply to the wide-character string-handling functions. In addition, Windows systems support lstrcpy, lstrcat, and lstrcpyn, and the Windows shell contains similar functions, such as StrCpy, StrCat, and StrCpyN exported from Shlwapi.dll. Although the lstr family of calls varies a little in the details and the calls work with both single-byte and multibyte character sets depending on how an LPTSTR ends up being defined by the application, they have the same problems as the more familiar ANSI versions.

Function Comment
strcpy The strcpy function is inherently unsafe and should be used rarely, if at all.

If either the destination or the source buffer is null, you end up in the exception handler. The greatest problem is that if the source string is longer than the destination buffer, an overflow occurs.

strncpy This function is safer than its strcpy, but passing in a null or otherwise illegal pointer for source or destination will cause exceptions.
sprintf There is almost no way to use this function safely. It is not easy to verify that the buffer is long enough for the data before calling sprintf.
_snprintf This function is flexible and safe, but it does not guarantee the buffer is null-terminated. Specify the character count as one less than the buffer size to always allow room for the trailing null character, and always null-terminate the last character of the buffer.
Standard Template Library Strings (STL) When you write C++ code you can use the STL. The STL has several useful member functions you can use to find characters and strings within another string and truncate the string.
gets and fgets Do not use gets. There is no way to know whether gets will overflow the buffer. Use fgets or a C++ stream object instead

Copyright © 2005 Microsoft Corporation.
All rights reserved.