bug-mes
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[PATCH] ntoab: Fix buffer underflow with large integer.


From: Michael Forney
Subject: [PATCH] ntoab: Fix buffer underflow with large integer.
Date: Sat, 13 Apr 2024 11:43:12 -0700

With base == 8, -2^63 is converted as -1000000000000000000000, which
is 24 bytes long (including terminating nul), so we need at least
this much space in the __itoa_buf.

* lib/mes/ntoab.c (ntoab): Allocate enough space for longest string,
  and update assert with lowest possible base. Don't decrement
  pointer below start of buffer, even temporarily.
---
 lib/mes/ntoab.c | 17 ++++++++---------
 1 file changed, 8 insertions(+), 9 deletions(-)

diff --git a/lib/mes/ntoab.c b/lib/mes/ntoab.c
index c8827503..acdeb8db 100644
--- a/lib/mes/ntoab.c
+++ b/lib/mes/ntoab.c
@@ -50,12 +50,10 @@ char *
 ntoab (long x, unsigned base, int signed_p)
 {
   if (__itoa_buf == 0)
-    __itoa_buf = malloc (20);
-  char *p = __itoa_buf + 11;
+    __itoa_buf = malloc (24);
+  char *p = __itoa_buf + 23;
 
-  p[0] = 0;
-  p = p - 1;
-  assert_msg (base > 0, "base > 0");
+  assert_msg (base >= 8, "base >= 8");
 
   int sign_p = 0;
   size_t i;
@@ -71,22 +69,23 @@ ntoab (long x, unsigned base, int signed_p)
   else
     u = x;
 
+  p[0] = 0;
   do
     {
+      p = p - 1;
       u = __mesabi_uldiv (u, b, &i);
       if (i > 9)
         p[0] = 'a' + i - 10;
       else
         p[0] = '0' + i;
-      p = p - 1;
     }
   while (u != 0);
 
-  if (sign_p && p[1] != '0')
+  if (sign_p && p[0] != '0')
     {
-      p[0] = '-';
       p = p - 1;
+      p[0] = '-';
     }
 
-  return p + 1;
+  return p;
 }
-- 
2.44.0




reply via email to

[Prev in Thread] Current Thread [Next in Thread]