[PATCH] fix null-pointer behavior in fmt and fmtlist functions

From: John Regan <john_at_jrjrtech.com>
Date: Tue, 5 Feb 2019 18:12:24 +0000

This fixes a segfault when a user calls uint320_fmt(NULL,...),
and makes the fmtlist functions return the correct number of
characters when called with NULL.
---
 src/libstddjb/fmtscan-internal.h | 23 +++++++++++------------
 1 file changed, 11 insertions(+), 12 deletions(-)
diff --git a/src/libstddjb/fmtscan-internal.h b/src/libstddjb/fmtscan-internal.h
index 34994a0..0e68788 100644
--- a/src/libstddjb/fmtscan-internal.h
+++ b/src/libstddjb/fmtscan-internal.h
_at_@ -118,11 +118,8 @@ size_t uint##bits##_fmtlist (char *s, uint##bits##_t const *tab, size_t n) \
   { \
     size_t w = uint##bits##_fmt(s, tab[i]) ; \
     len += w ; \
-    if (s) \
-    { \
-      s += w ; \
-      if (i < n-1) { *s++ = ',' ; len++ ; } \
-    } \
+    if (s) s += w ; \
+    if (i < n-1) { len++ ; if (s)  *s++ = ',' ; } \
   } \
   return len ; \
 } \
_at_@ -146,9 +143,14 @@ size_t uint##bits##_fmt_base (char *s, uint##bits##_t x, unsigned int base) \
 #define FMTB0(bits) \
 size_t uint##bits##0_fmt_base (char *s, uint##bits##_t x, size_t n, unsigned int base) \
 { \
+  size_t r = n ; \
   size_t len = uint##bits##_fmt_base(0, x, base) ; \
-  while (n-- > len) *s++ = '0' ; \
-  return uint##bits##_fmt_base(s, x, base) ; \
+  if (s) \
+  { \
+    while (n-- > len) *s++ = '0' ; \
+    len = uint##bits##_fmt_base(s, x, base) ; \
+  } \
+  return len > r ? len : r ; \
 } \
 
 #define FMTS(bits) \
_at_@ -167,11 +169,8 @@ size_t int##bits##_fmtlist (char *s, int##bits##_t const *tab, size_t n) \
   { \
     size_t w = int##bits##_fmt(s, tab[i]) ; \
     len += w ; \
-    if (s) \
-    { \
-      s += w ; \
-      if (i < n-1) { *s++ = ',' ; len++ ; } \
-    } \
+    if (s) s += w ; \
+    if (i < n-1) { len++ ; if (s) *s++ = ',' ; } \
   } \
   return len ; \
 } \
-- 
2.17.1
Received on Tue Feb 05 2019 - 18:12:24 UTC

This archive was generated by hypermail 2.3.0 : Sun May 09 2021 - 19:38:49 UTC