commit 1c2ad3584e9473c7327a908b2435fdcdbe535777
parent b491da26d599c2a3a21ec0e5eae5ecbd1da1f5cf
Author: Roberto E. Vargas Caballero <k0ga@shike2.net>
Date: Fri, 17 Apr 2026 22:25:27 +0200
libc/stdio: Fix sprintf functions
The sprintf family of functions was reusing the code from the
snprintf functions just with a number that was big enough for
any string, and we thougth that SIZE)MAX was the best option
for it, but it just just wrong because due to the modular
behaviour of pointer aritmetic adding SIZE_MAX to a pointer
is just equivalent to decrease the pointer, and it meant that
all the sprint function were just silently ignoring the bytes
printed to the string because this is the expected behaviour in
snprintf when you don't have enough room for new bytes, you just
discard them but keep the count.
Diffstat:
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/src/libc/stdio/vsprintf.c b/src/libc/stdio/vsprintf.c
@@ -1,4 +1,3 @@
-#include <limits.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
@@ -8,5 +7,13 @@
int
vsprintf(char *restrict s, const char *restrict fmt, va_list va)
{
- return vsnprintf(s, SIZE_MAX, fmt, va);
+ /*
+ * we used to use SIZE_MAX here, but that is just
+ * wrong because we build a rp pointer that in that
+ * case it is just wp - 1 by definition. As it
+ * is impossible to span an object further than
+ * the end of the memory space we can use the number
+ * of bytes until the end of the address space.
+ */
+ return vsnprintf(s, (char *)-1 - s, fmt, va);
}