UB status of snprintf on invalid ptr+size combination?

Siddhesh Poyarekar siddhesh@gotplt.org
Wed Mar 15 15:54:46 GMT 2023


On 2023-03-15 05:22, Andreas Schwab via Libc-alpha wrote:
> On Mär 14 2023, Paul Eggert wrote:
> 
>> For example, it's valid for snprintf to be implemented this way:
>>
>>    int
>>    snprintf (char *buf, size_t size, char const *fmt, ...)
>>    {
>>       char *buf_limit = buf + size;
>>       ...
>>    }
>>
>> even though this would have undefined behavior if BUF points to a
>> character array smaller than SIZE.
> 
> Since it is part of the implementation it is irrelevant from the POV of
> the standard.  The implementation does not have to abide to the C
> standard, as long as it properly implements the interface constraints.
> 
> What matters is the wording of the standard.  The POSIX standard is more
> explicit here: "with the addition of the n argument which states the
> size of the buffer referred to by s."  Probably the C standard should be
> clarified.

+1, the C standard wording ought to mirror POSIX here.  FWIW, when built 
with fortification, this code will abort prematurely because it 
considers passed size being greater than the buffer size as being unsafe.

Thanks,
Sid


More information about the Libc-alpha mailing list