This is the mail archive of the
libc-alpha@sources.redhat.com
mailing list for the glibc project.
Re: PATCH: safe string copy and concetation
- To: <libc-alpha at sources dot redhat dot com>
- Subject: Re: PATCH: safe string copy and concetation
- From: "Scott Marks" <Scott at CourtlandCapital dot com>
- Date: Thu, 10 Aug 2000 10:15:14 -0400
X-PMC-CI-e-mail-id: 13410
>> Certainly, strlcpy is easy:
>>
>> #define strlcpy(a, b, c) sprintf(a, "%.*s", b, (int) ((c)-1))
>>
No, no, no! You guys ever read the original documentation!? The point is
that both strlcat and strlcpy return the *total* string length in the case
that the operation succeeds, but, if the operation does not succeed, return
the *total* length without doing anything! This way, a simple
BUFSIZE<=retval check lets you detect and deal with the error. You get
*more* efficiency since the "strlen" part of the process is combined with
the cpy/cat:
char buf[BUFSIZE];
int len;
len = strlcpy ( buf , prefix , BUFSIZE );
if ( BUFSIZE <= len )
signal_error ( EBUFTOOSMALL );
len = strlcat ( buf , middle , BUFSIZE );
if ( BUFSIZE <= len )
signal_error ( EBUFTOOSMALL );
len = strlcat ( buf , suffix , BUFSIZE );
if ( BUFSIZE <= len )
signal_error ( EBUFTOOSMALL );
Now, *excuuuse me*, but this seems *efficient* and *safe* to me! Not to
mention mondo more elegant than (1) maintaining fragile string length
invariants or (2) relatively cryptic one-liners like
*((char *) mempcpy (dst, src, n)) = '\0';
Plus, if you really like one-liners, try simply:
if ( BUFSIZE <= strlcat ( buf , suffix , BUFSIZE ) )
signal_error ( EBUFTOOSMALL );
Scott Marks
Courtland Capital Management