[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: alternatives to 'strlcpy'

From: Paul Eggert
Subject: Re: alternatives to 'strlcpy'
Date: Thu, 28 Sep 2017 15:19:07 -0700
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.3.0

On 09/28/2017 11:39 AM, Bruno Haible wrote:
in BSD, it is common practice to try
a call with a fixed-size stack-allocated or statically allocated buffer,
and try dynamic memory only when this first attempt fails.

This doesn't match my experience with BSD application code, where the most common practice is to call strlcpy and ignore the return value. I looked at the source for OpenSSH 7.5 (the current version). Of its 56 calls to strlcpy, only 15 check the return value, and none of these calls try dynamic allocation later (they all simply fail in the caller somehow). Of the 41 calls that ignore the return value, sometimes this is a bug and sometimes not, and often when it is not a bug plain strcpy would work as well. So the strlcpy API appears to be a poor fit for OpenSSH's needs.

/* Copies the string SRC, possibly truncated, into the bounded memory area
    If the result fits, it returns 0.
    If DSTSIZE is 0, it returns -1 and sets errno to EINVAL.
    If DSTSIZE is nonzero and the result does not fit, it produces a NUL-
    terminated truncated result, and returns -1 and sets errno to E2BIG.  */
extern int strgcpy (char *__dst, size_t __dstsize, const char *__src)
   __attribute__ ((__nonnull__ (1, 3)))
   __attribute__ ((__warn_unused_result__));

Some comments:

* I suggest a name that does not begin with "str", as that's reserved to the implementation.

* I too am bothered by this function setting errno (and using two different errno values to boot); it'd be simpler for it to just to return a value, or to abort if the destination is too small.

* If the intent is that this function be used for test-case code that aborts if the source is too long, then I suggest that the function simply return 'void' and abort if the source is too long, as that would be more convenient for the callers. If the intent is something else, I'd like to know what it is so that I can think about it more.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]