I'm refactoring some HTTP client code I wrote a while back and in the
process I'm tightening up some of my string processing code (most of
which involves parsing, replacing, concatenating strings etc.).
I'm reading that it is better to use str functions like "snprintf" and
to avoid using "strcat" altogether since the former more explicit
protection against buffer overflow etc. Is this sort of comment good
advice ?
You'll have to judge that for yourself, I'm afraid. Certainly the
overflow-guarding functions provide an extra check that's not
present in their non-guarding alternatives. However, people often
use strncpy and strncat incorrectly, and since buffer overflow has
to be handled somehow, some argue that you ought to find how long
your source strings are *before* trying to copy them - which makes
the additional guarding largely pointless.
My priorities are security, standards (ANSI C/POSIX) then performance.
Personally, I generally use the guarded versions (strncpy, strncat,
snprintf) in most cases. In some places overflow is handled by
silent truncation, because the program specification allows that; in
others the code has checked lengths already but uses the guarded
versions anyway just to protect against present or future logic
errors that might let an over-long parameter through. I'm not
concerned about the performance penalty, which is likely to be
negligible.
If you're concerned about standards, though, note that snprintf was
only added to the C standard in 1999, and that earlier versions of
the POSIX (SUS, etc) standard was inferior (it didn't let snprintf
distinguish between end-of-buffer and invalid-format conditions).
The current Microsoft Visual C snprintf implementation is still
broken this way, and some older Unix ones are as well (all of those
from HP, IIRC).
If your first priority is security - which I approve of - and you're
going to use C,[1] then I would recommend using the guarded string-
handling functions, or writing your own, or picking up someone else's
(if it's compliant and after vetting it). But I'd also recommend
thinking about how overflow should be handled, when silent truncation
is appropriate, and when the application should do something else;
and I'd recommend making explicit length checks where they seem
appropriate and not just relying on the string-handling functions to
do that for you.
1. There's been a lengthy flamewar recently in sci.crypt over whether
C is inherently bad for software security. I'm staying out of it,
as I think all the useful arguments on both sides have already been
aired.