21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

All of the string-handling improvements we’ve discussed so far operate using traditional<br />

C-style NULL-terminated strings. While strlcat( ), strlcpy( ), and Microsoft’s<br />

new string-handling functions are vast improvements over the traditional C stringhandling<br />

functions, they all still require diligence on the part of the programmer to<br />

maintain information regarding the allocated size of destination buffers.<br />

An alternative to using traditional C style strings is to use the SafeStr library, which is<br />

available from http://www.zork.org/safestr/. The library is a safe string implementation<br />

that provides a new, high-level data type for strings, tracks accounting information<br />

for strings, and performs many other operations. For interoperability purposes,<br />

SafeStr strings can be passed to C string functions, as long as those functions use the<br />

string in a read-only manner. (We discuss SafeStr in some detail in Recipe 3.4.)<br />

Finally, applications that transfer strings across a network should consider including<br />

a string’s length along with the string itself, rather than requiring the recipient to rely<br />

on finding the NULL-terminating character to determine the length of the string. If the<br />

length of the string is known up front, the recipient can allocate a buffer of the proper<br />

size up front and read the appropriate amount of data into it. The alternative is to<br />

read byte-by-byte, looking for the NULL-terminator, and possibly repeatedly resizing<br />

the buffer. Dan J. Bernstein has defined a convention called Netstrings (http://cr.yp.to/<br />

proto/netstrings.txt) for encoding the length of a string with the strings. This protocol<br />

simply has you send the length of the string represented in ASCII, then a colon, then<br />

the string itself, then a trailing comma. For example, if you were to send the string<br />

“Hello, World!” over a network, you would send:<br />

14:Hello, World!,<br />

Note that the Netstrings representation does not include the NULL-terminator, as that<br />

is really part of the machine-specific representation of a string, and is not necessary<br />

on the network.<br />

Using C++<br />

When using C++, you generally have a lot less to worry about when using the standard<br />

C++ string library, std::string. This library is designed in such a way that<br />

buffer overflows are less likely. Standard I/O using the stream operators (>> and

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!