Thread (7 messages) 7 messages, 2 authors, 2025-12-06

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-05 20:46:44

Hi,

Here's how this patch changes the formatted page:

$ MANWIDTH=72 diffman-git HEAD
--- HEAD^:man/man3/snprintf.3
+++ HEAD:man/man3/snprintf.3
@@ -33,7 +33,8 @@ DESCRIPTION
      to the character string str instead of a stream.
 
      The functions snprintf() and vsnprintf() write at most size bytes
-     (including the terminating null byte ('\0')) to str.
+     (including the terminating null byte ('\0')) to str (but see
+     BUGS).
 
      The functions vsprintf() and vsnprintf() are equivalent to the
      functions sprintf() and snprintf(), respectively, except that they
@@ -132,6 +133,16 @@ BUGS
      Use snprintf() and vsnprintf() instead (or asprintf(3) and
      vasprintf(3)).
 
+   snprintf(), vsnprintf()
+     If size is negative, these functions will behave as if the size
+     was some unreasonably high value.  This turns these functions es‐
+     sentially equivalent to [v]sprintf(), and thus likely to overflow
+     the buffer.  It is the programmer’s responsibility to pass a non‐
+     negative size.
+
+     For historic reasons, the size parameter is of type int, which
+     makes it relatively easy to pass a negative value.
+
 EXAMPLES
      To allocate a sufficiently large string and print into it (code
      correct for both glibc 2.0 and glibc 2.1):

Cheers,
Alex

On Fri, Dec 05, 2025 at 09:14:14PM +0100, Alejandro Colomar wrote:
quoted hunk ↗ jump to hunk
Reported-by: Serge Hallyn <serge@hallyn.com>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
---
 man/man3/snprintf.3 | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
diff --git a/man/man3/snprintf.3 b/man/man3/snprintf.3
index dca9fc3ef..e6bb9547d 100644
--- a/man/man3/snprintf.3
+++ b/man/man3/snprintf.3
@@ -54,7 +54,8 @@ .SH DESCRIPTION
 write at most
 .I size
 bytes (including the terminating null byte (\[aq]\[rs]0\[aq])) to
-.IR str .
+.I str
+(but see BUGS).
 .P
 The functions
 .BR vsprintf ()
@@ -242,6 +243,24 @@ .SS sprintf(), vsprintf()
 .BR asprintf (3)
 and
 .BR vasprintf (3)).
+.SS snprintf(), vsnprintf()
+If
+.I size
+is negative,
+these functions will behave
+as if the size was some unreasonably high value.
+This turns these functions essentially equivalent to
+.RB [ v ] sprintf (),
+and thus likely to overflow the buffer.
+It is the programmer's responsibility to pass a non-negative
+.IR size .
+.P
+For historic reasons,
+the
+.I size
+parameter is of type
+.IR int ,
+which makes it relatively easy to pass a negative value.
 .\" .P
 .\" Linux libc4.[45] does not have a
 .\" .BR snprintf (),
-- 
2.51.0
-- 
<https://www.alejandro-colomar.es>

Attachments

Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help