From c4d8d937d5953930ba00a6f40ce3fdd17273f68e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karel=20Ko=C4=8D=C3=AD?= Date: Wed, 21 Aug 2024 13:10:55 +0200 Subject: [PATCH] libs/libc/obstack: correctly append null byte at the end of string obstack_printf and obstack_vprintf should terminate the C string with null byte but lib_vsprintf doesn't do it. It must be done on top of that unless we get unterminated string. This is fix to be consistent with GlibC behavior. This also includes minor tweak to use obstack_1grow directly instead of calling obstack_puts. --- libs/libc/obstack/lib_obstack_vprintf.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/libs/libc/obstack/lib_obstack_vprintf.c b/libs/libc/obstack/lib_obstack_vprintf.c index 706360a5518..856b6fdc47e 100644 --- a/libs/libc/obstack/lib_obstack_vprintf.c +++ b/libs/libc/obstack/lib_obstack_vprintf.c @@ -54,8 +54,11 @@ static int obstack_puts(FAR struct lib_outstream_s *self, static void obstack_putc(FAR struct lib_outstream_s *self, int ch) { - char tmp = ch; - obstack_puts(self, &tmp, 1); + FAR struct obstack_stream *stream = (FAR struct obstack_stream *)self; + + DEBUGASSERT(self); + + obstack_1grow(stream->h, ch); } /**************************************************************************** @@ -93,5 +96,14 @@ int obstack_vprintf(FAR struct obstack *h, FAR const char *fmt, va_list ap) outstream.common.nput = 0; outstream.h = h; - return lib_vsprintf(&outstream.common, fmt, ap); + int nbytes = lib_vsprintf(&outstream.common, fmt, ap); + + if (nbytes < 0) + { + obstack_free(h, obstack_finish(h)); + return ERROR; + } + + obstack_1grow(h, '\0'); + return nbytes; }