diff Objects/unicodeobject.c @ 27039:b30fe4dcc697 2.2

Backport MAL's patch for bug #659709: bogus computation of float length
author Raymond Hettinger <python@rcn.com>
date Thu, 02 Jan 2003 22:08:39 +0000
parents b564ec4b7e5b
children 6ba940cd99ef
line wrap: on
line diff
--- a/Objects/unicodeobject.c	Thu Jan 02 04:54:22 2003 +0000
+++ b/Objects/unicodeobject.c	Thu Jan 02 22:08:39 2003 +0000
@@ -5250,20 +5250,31 @@
 	prec = 6;
     if (type == 'f' && (fabs(x) / 1e25) >= 1e25)
 	type = 'g';
+    /* Worst case length calc to ensure no buffer overrun:
+
+       'g' formats:
+	 fmt = %#.<prec>g
+	 buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
+	    for any double rep.)
+	 len = 1 + prec + 1 + 2 + 5 = 9 + prec
+
+       'f' formats:
+	 buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
+	 len = 1 + 50 + 1 + prec = 52 + prec
+
+       If prec=0 the effective precision is 1 (the leading digit is
+       always given), therefore increase the length by one. 
+
+    */
+    if ((type == 'g' && buflen <= (size_t)10 + (size_t)prec) ||
+	(type == 'f' && buflen <= (size_t)53 + (size_t)prec)) {
+	PyErr_SetString(PyExc_OverflowError,
+			"formatted float is too long (precision too large?)");
+	return -1;
+    }
     PyOS_snprintf(fmt, sizeof(fmt), "%%%s.%d%c",
-		  (flags & F_ALT) ? "#" : "", prec, type);
-    /* worst case length calc to ensure no buffer overrun:
-         fmt = %#.<prec>g
-         buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
-            for any double rep.)
-         len = 1 + prec + 1 + 2 + 5 = 9 + prec
-       If prec=0 the effective precision is 1 (the leading digit is
-       always given), therefore increase by one to 10+prec. */
-    if (buflen <= (size_t)10 + (size_t)prec) {
-	PyErr_SetString(PyExc_OverflowError,
-	    "formatted float is too long (precision too long?)");
-	return -1;
-    }
+		  (flags&F_ALT) ? "#" : "",
+		  prec, type);
     return usprintf(buf, fmt, x);
 }