On Wed, Jun 26, 2024 at 05:33:55PM GMT, Paul Eggert wrote: > On 6/26/24 07:57, Bruno Haible wrote: > > Po Lu wrote: > > > I believe that the semantics of the POSIX specification of this GNU > > > function omit the implied guarantee that strnlen will never examine > > > bytes beyond the first null byte > > > > There is no such guarantee, not even implied. > > There seems to be some confusion here. Here's what POSIX.1-2024 says: > > "The strnlen() function shall compute the smaller of the number of bytes in > the array to which s points, not including any terminating NUL character, or > the value of the maxlen argument. The strnlen() function shall never examine > more than maxlen bytes of the array pointed to by s." > > This means it's OK to call strnlen ("", SIZE_MAX), because the second arg of > strnlen can be larger than the number of bytes in the byte array that the > first arg points to, so long as that array contains a null byte. strnlen is > unusual in this sense.
Be careful: there is an open bug against POSIX 2024 and being worked in parallel with the C standard to tweak the requirements on strnlen() to be more precise: https://www.austingroupbugs.net/view.php?id=1834#c6830 The current draft of proposed wording would have the C standard state: 2 The strnlen function counts not more than n characters (a null character and characters that follow it are not counted) in the array to which s points. At most the first n characters of s shall be accessed by strnlen. at which point, strnlen("", SIZE_MAX) _is_ allowed to _access_ beyond the NUL byte, so long as it does not access beyond n bytes. While most implementations stop at the first NUL byte, they are not required to do so, at which point you CAN trigger a crash for accessing beyond the bounds of your actual string. -- Eric Blake, Principal Software Engineer Red Hat, Inc. Virtualization: qemu.org | libguestfs.org