This is the mail archive of the libc-alpha@sources.redhat.com mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: PATCH: safe string copy and concetation


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]