FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
C++
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
September 08, 2006

Illusions of Safety

(Page 3 of 5)

Prevention by Design

Prevention by design means, simply, designing your application so that low-level code doesn't need to check buffer sizes. If you check the data at the point where it enters your application, you can call low-level functions without worrying about buffer overruns. The code to copy text into a buffer simply copies text into a buffer:

void process(const char *txt)
{ /* strlen(txt) must be less than MAX_LINE */
char buf[MAX_LINE];
assert(strlen(txt) < MAX_LINE);
strcpy(buf, txt);
/* continue normal processing */

The design of this function pushes the responsibility for avoiding buffer overruns up into its caller. By putting an assert in the function, you provide a debugging check to help assure that you've properly validated the data higher up. Functions that call this function will, in turn, push the checking up into their callers [5], all the way to the function that creates the text string. By design, each intermediate function must be called only with a text string that fits in this buffer:

void middle(const char *txt)
{ /* strlen(txt) must be less than MAX_LINE */
process(txt);}

void creator(FILE *fp) { /* read and process lines of up to MAX_LINE-1 characters */ char buf[MAX_LINE]; while (fgets(buf, MAX_LINE, fp)) middle(buf); }

This function uses the same size buffer for its input as we used deeper down, so the check it has to make to ensure that its buffer doesn't overflow does double duty by also ensuring that the low-level function's buffer doesn't overflow. By pushing the checking up to the function that creates the text string, we've eliminated one validity check entirely. In a real application, this approach eliminates far more than one check, and the application becomes simpler, smaller, and faster.

The biggest drawback of eliminating buffer overruns by design is that it requires careful attention from the application's designers to ensure that all buffer sizes are properly specified, so that the high-level tests are sufficient. Validating data at the point where it's used instead of where it's created doesn't require as much thought. It's easier to find places where the check is missing, so it's easier to enforce the discipline of validation.

Previous Page | 1 Buffer Overruns | 2 Prevention by Brute Force | 3 Prevention by Design | 4 Slogans | 5 TR 24731 and Safety Next Page
TOP 5 ARTICLES
No Top Articles.



MICROSITES
FEATURED TOPIC

ADDITIONAL TOPICS

INFO-LINK