|
|||||||||||
|
RE: safe strcpy()?
From: Daniel Reed <n(at)cs.rpi.edu>
Date: Wed Jan 29 2003 - 17:04:58 EST
This discussion, while bringing up some interesting points, largely misses the point of what "safe" programming involves. For example, in one package I maintain I have to deal with converting printable strings into HTML entities. Due to protocol constraints, it's possible that the encoded string might be too large to send whole, so I split such strings at the entity boundary (see below). For each character in a printable string, I check whether it needs to be encoded or not. Once I have determined what entity will be sent in place of the original character, I check whether adding that entity to my buffer would push it past its limit. If so, I stop copying and send the buffer along before attempting to add the next character. This way, if the protocol I was dealing with limited strings to (let's say) 22 characters, a string such as:
"1 < 3 - That's the truth"
1234567890123456789012 "1 < 3 - " " That's the truth" instead of the less desirable: 1234567890123456789012 "1 < 3 -  " ";That's the truth" The former would decode into "I < 3 - " + " That's the truth", and could be glued back to the original "I < 3 - That's the truth", whereas the latter would decode into "I < 3 -  " + ";That's the truth" and be recombined into "I < 3 - That's the truth". Whoops. Now, the code in question was originally written with a blind fear of buffer overflows clouding the original authour's style, and worked something like:
if (input[i] == ' ') {
strncpy(output+outputpos, sizeof(output)-outputpos, " ");
outputpos += sizeof(" ")-1;
}
This would allow a space occuring near the end of "output" to be truncated into " ", as in the example above. The new code is similar to:
if (input[i] == ' ')
if ((outputpos + sizeof(" ")) < sizeof(output)) {
strcpy(output+outputpos, " ");
outputpos += sizeof(" ")-1;
} else
break;
This allows the loop to break once the "output" buffer has become filled, for all intents and purposes, and will allow the procedure to empty "output" and start from where it left off (so the space wouldn't appear at all in the current line, and would instead appear whole in the next line). Security is indeed very important, and if more people made secure codewriting a priority, a lot of our lives would become much easier. However, there are no magic wands in programming: -- Daniel ReedReceived on Wed Jan 29 18:39:46 2003 This archive was generated by hypermail 2.1.8 : Wed Aug 23 2006 - 14:02:46 EDT |
||||||||||
|
|||||||||||