Re: strcpy versus strncpy

Kragen (kragen@POBOX.COM)
Tue, 03 Mar 1998 10:39:49 -0500

On Mon, 2 Mar 1998, Daniel Reed wrote:
> On Tue, 3 Mar 1998, Morten Welinder wrote:
> ) (truncating strings is bad because it changes their semantics, therefore,
> ) strncpy is bad)
>
> . . . Under any user, using a static
> buffer with strncpy/snprintf/vsnprintf, buffer overflows are significantly
> reduced (if not eliminated), resource starvation is significantly reduced
> (if not eliminated), and at worse an incoming, legitimate message will be
> bounced because it overflows a buffer.

Well, the question is, what do you do with strings that are too long? Do
you (a) dynamically allocate memory for them, (b) silently truncate them,
(c) return an error, or (d) let them overflow your buffers and crash your
program in interesting and possibly-exploitable ways?

M. W.'s point was that (b), which is strncpy's default behavior, is bad,
and (a) is better.

Your point is that (c) is better than (a), because (1) dynamically
allocating memory is error-prone and (2) dynamically allocating memory
is an opening for DoS atacks.

I think that either (a) or (c) is better than either (b) or (d). I
don't think anyone will disagree.

I do think that (b) is better than (d).

I think that (c) is better -- as you said -- in situations where there
is the potential for DoSes.

strncpy, strncat, snprintf, et al., don't support (c) very well. Small
wrapper functions to do (c) (much like djb's stralloc functions, which
support (a), used throughout qmail) would greatly facilitate it.

The checking required to make the s*n* functions do (c) instead of (b)
is roughly analogous to the checking required to make the s* functions
do (c) instead of (d).

Kragen