[review] manual: Clarify strnlen, wcsnlen, strndup null termination behavior

Florian Weimer fweimer@redhat.com
Wed Oct 30 10:55:00 GMT 2019


* Andreas Schwab:

> On Okt 30 2019, Florian Weimer (Code Review) wrote:
>
>> +Note that @var{s} must be an array of at least @var{maxlen} bytes.  It
>> +is undefined to call @code{strnlen} on a shorter array, even if it is
>> +known that the shorter array contains a null terminator.
>
> This is not true.  strnlen _always_ stops before the null byte.

This is not how it is specified in POSIX.

Our generic implementation of strnlen performs out-of-bounds pointer
arithmetic in that case, and it looks really iffy:

  const char *char_ptr, *end_ptr = str + maxlen;
…
  if (__glibc_unlikely (end_ptr < str))
    end_ptr = (const char *) ~0UL;

GCC does the right thing on x86-64, I think, but that's far from
guaranteed.

And what about wcsnlen?

Thanks,
Florian



More information about the Libc-alpha mailing list