[Top][All Lists]

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

new module 'strlcpy'

From: Bruno Haible
Subject: new module 'strlcpy'
Date: Thu, 28 Sep 2017 00:46:19 +0200
User-agent: KMail/5.1.3 (Linux/4.4.0-93-generic; KDE/5.18.0; x86_64; ; )

Paul Eggert wrote:
> @@ -48,7 +48,8 @@ get_locale_dependent_values (struct locale_dependent_values 
> *result)
>    snprintf (result->numeric, sizeof (result->numeric),
>              "%g", 3.5);
>    /* result->numeric is usually "3,5" */
> -  strcpy (result->time, nl_langinfo (MON_1));
> +  strncpy (result->time, nl_langinfo (MON_1), sizeof result->time - 1);
> +  result->time[sizeof result->time - 1] = '\0';
>    /* result->time is usually "janvier" */
>  }

This change has replaced code with 1 drawback
  - The string copy may overrun the buffer.
by code with 3 drawbacks
  - The string copy may be silently truncated.
  - The code needs 2 lines, instead of 1 line.
  - In the common cases, the large result buffer gets needlessly filled
    with NULs.

I think the best way to deal with this situation is the function 'strlcpy':

  ASSERT (strlcpy (result->time, nl_langinfo (MON_1), sizeof result->time) < 
sizeof result->time);

This way,
  - The string copy will not overrun the buffer.
  - The string copy will always be NUL-terminated.
  - Silent truncation does not occur.
  - The code fits in one line.
  - The code is not needlessly inefficient.

Here's a proposal to add 'strlcpy' to gnulib.

Yes, I have read the relevant documentation:

and the discussions:

The major argument against strlcpy is that it is not fool-proof:
If the caller ignores the return value, silent truncation can occur.
To prevent this, the proposed patch declares strlcpy with
__attribute__((__warn_unused_result__)) on all platforms.


Attachment: 0001-New-module-strlcpy.patch
Description: Text Data

Attachment: 0002-Tests-for-module-strlcpy.patch
Description: Text Data

reply via email to

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