postgres.git / summary / log / commit / refs
commit ec65cbc00b2ccc82996e1c94b534e1fbf61fbcd1
Author: Tom Lane <tgl@sss.pgh.pa.us>
Date: Fri Oct 30 15:03:13 2026 +0000
First released in: 14.25, 15.20, 16.16, 17.12, 18.7, 19.0
Return INT_MAX or INT_MIN from strtoint() on overflow.
Previously, strtoint() set errno to ERANGE on overflow but returned
the result of casting the long value to int. When the value is outside
the range of int, this produces an implementation-defined result that
cannot reliably indicate the direction of overflow. POSIX requires
strtol() to return exactly LONG_MAX or LONG_MIN on overflow, which
permits safe sign-testing or range-testing. By analogy, make
strtoint() return INT_MAX or INT_MIN on overflow.
Back-patch, since future bug fixes may expect this behavior.
Author: Chao Li <li.evan.chao@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/A33EE17C-D014-4980-B3DD-AC51588A06EC@gmail.com
Backpatch-through: 14
src/common/string.c | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/src/common/string.c b/src/common/string.c
index d8a3129c3ba..7adcd602aeb 100644
--- a/src/common/string.c
+++ b/src/common/string.c
@@ -21,6 +21,8 @@
#include "postgres_fe.h"
#endif
+#include <limits.h>
+
#include "common/string.h"
@@ -45,6 +47,9 @@ pg_str_endswith(const char *str, const char *end)
/*
* strtoint --- just like strtol, but returns int not long
+ *
+ * The result is clamped to INT_MIN..INT_MAX, not LONG_MIN..LONG_MAX,
+ * but otherwise this has the same behavior as strtol.
*/
int
strtoint(const char *pg_restrict str, char **pg_restrict endptr, int base)
@@ -53,7 +58,10 @@ strtoint(const char *pg_restrict str, char **pg_restrict endptr, int base)
val = strtol(str, endptr, base);
if (val != (int) val)
+ {
+ val = (val < 0) ? INT_MIN : INT_MAX;
errno = ERANGE;
+ }
return (int) val;
}
[parent: 7ba657cba130]