From f43c123c0d33b43b2040236e9439a467230e8f2c Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Thu, 3 Jul 2025 20:22:25 +0200 Subject: [PATCH 1/2] Fix tolower()/toupper() implementation to not lead to undefined behavior Fixes #4537 --- src/iso19111/internal.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/iso19111/internal.cpp b/src/iso19111/internal.cpp index c6ba11c73b..f9f3f738f2 100644 --- a/src/iso19111/internal.cpp +++ b/src/iso19111/internal.cpp @@ -129,8 +129,9 @@ std::string tolower(const std::string &str) { std::string ret(str); - for (size_t i = 0; i < ret.size(); i++) - ret[i] = static_cast(::tolower(ret[i])); + for (char &ch : ret) + ch = + (ch >= 'A' && ch <= 'Z') ? static_cast(ch + ('a' - 'A')) : ch; return ret; } @@ -144,8 +145,9 @@ std::string toupper(const std::string &str) { std::string ret(str); - for (size_t i = 0; i < ret.size(); i++) - ret[i] = static_cast(::toupper(ret[i])); + for (char &ch : ret) + ch = + (ch >= 'a' && ch <= 'z') ? static_cast(ch - ('a' - 'A')) : ch; return ret; } From 127ba1343f35edd571f6c3230060acc72e9c3211 Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Fri, 4 Jul 2025 09:59:27 +0200 Subject: [PATCH 2/2] Avoid undefined behavior with isgraph() use --- src/dmstor.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/dmstor.cpp b/src/dmstor.cpp index 7dca18a0b8..8f34df8fc5 100644 --- a/src/dmstor.cpp +++ b/src/dmstor.cpp @@ -46,7 +46,9 @@ double dmstor_ctx(PJ_CONTEXT *ctx, const char *is, char **rs) { * It is possible that a really odd input (like lots of leading zeros) * could be truncated in copying into work. But ... */ - while ((isgraph(*p) || *p == DEG_SIGN1 || *p == DEG_SIGN2) && --n) + while ((isgraph(static_cast(*p)) || *p == DEG_SIGN1 || + *p == DEG_SIGN2) && + --n) *s++ = *p++; *s = '\0'; int sign = *(s = work);