Re: [PATCH 2/2] man/man3/snprintf.3: BUGS: snprintf(3) with a negative size is essentially UB
From: Alejandro Colomar <alx@kernel.org>
Date: 2025-12-06 17:45:49
Attachments
- signature.asc [application/pgp-signature] 833 bytes
From: Alejandro Colomar <alx@kernel.org>
Date: 2025-12-06 17:45:49
Hi Serge, On Sat, Dec 06, 2025 at 11:33:54AM -0600, Serge Hallyn wrote:
quoted
Actually, I was completely wrong. The parameter is of type size_t. Only the return value is of type int. Have a lovely day! AlexRight, that's actually the danger. It's easy to pass in an int or ssize_t, and end up overflowing the buffer, even if you (the caller) check for > buflen in advance, by passing in a negative value. By the time you check the return value, it's too late.
ssize_t should be safe, as it has the same width as size_t. It should be impossible to have a negative value in ssize_t, because objects can't grow past PTRDIFF_MAX, which is --at least in all platforms we care about-- exactly the same as SSIZE_MAX. So, to pass a negative value, you would have to either write it literally, or do something really bad. malloc(3) can't possibly create an object that would result in a negative ssize_t. The problem would only exist with int, because int is easy to overflow. That is, the following code is fine: ssize_t x = _Countof(buf); snprintf(buf, x, ...); And it behaves exactly like this: size_t x = _Countof(buf); snprintf(buf, x, ...); However, the following is likely to result in a buffer overflow: int x = _Countof(buf); snprintf(buf, x, ...); Have a lovely day! Alex
"You just need to know (and not do that)", but if you are reviewing a patch and don't notice the extra s in ssize_t...
-- <https://www.alejandro-colomar.es>