https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84649

Martin Sebor <msebor at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|UNCONFIRMED                 |RESOLVED
         Resolution|---                         |INVALID

--- Comment #1 from Martin Sebor <msebor at gcc dot gnu.org> ---
Unlike for strncpy where the main goal of the warning is to help detect calls
that unintentionally leave the copy unterminated, for strncat (which always
appends a nul) the main goal is to help detect the possibility of a buffer
overflow.  A secondary goal is to detect unintended truncation of the source
string.

With that in mind the recommended use of the function is like so:

  char *append_leading_digits(char *cp, unsigned size, int i)
  {
    char buf[16];
    __builtin_sprintf(buf, "%2i ", i);
    __builtin_strncat(cp, buf, size - __builtin_strlen (cp) - 1);
    return cp;
  }

If you don't have access to the size of the buffer an alternative is to use
memcpy (it also doesn't prevent buffer overflow like the original but it
doesn't trigger a warning):

  char *append_leading_digits(char *cp, int i)
  {
    char buf[16];
    int n = __builtin_sprintf(buf, "%2i ", i);
    __builtin_memcpy(cp, buf, n < 4 ? n : 4);
    return cp;
  }

or, assuming there's at least 5 bytes worth of space in cp, simply:

  char *append_leading_digits(char *cp, int i)
  {
    __builtin_snprintf(cp, 5, "%2i ", i);
    return cp;
  }

(This last one will trigger a -Wformat-truncation warning at level 2 due to the
possible truncation.)

For more background on the philosophy behind the warning please see for
example:
https://www.us-cert.gov/bsi/articles/knowledge/coding-practices/strncpy-and-strncat

Since the warning is behaving as intended I'm going to resolve this report as
invalid.

Reply via email to