[flang-commits] [flang] d889a74 - [flang] Avoid UB in CharBlock Compare to C string (#147329)
via flang-commits
flang-commits at lists.llvm.org
Tue Jul 8 00:52:39 PDT 2025
Author: David Spickett
Date: 2025-07-08T08:52:36+01:00
New Revision: d889a7485f77c214ee57d0a74bf164237fdfa423
URL: https://github.com/llvm/llvm-project/commit/d889a7485f77c214ee57d0a74bf164237fdfa423
DIFF: https://github.com/llvm/llvm-project/commit/d889a7485f77c214ee57d0a74bf164237fdfa423.diff
LOG: [flang] Avoid UB in CharBlock Compare to C string (#147329)
The behaviour of strncmp is undefined if either string pointer is null
(https://en.cppreference.com/w/cpp/string/byte/strncmp.html).
I've copied the logic over from Compare to another CharBlock, which had
code to avoid UB in memcmp.
The test Preprocessing/kind-suffix.F90 was failing with UBSAN enabled,
and now passes.
Added:
Modified:
flang/include/flang/Parser/char-block.h
Removed:
################################################################################
diff --git a/flang/include/flang/Parser/char-block.h b/flang/include/flang/Parser/char-block.h
index 38f4f7b82e1ea..b3b1f04034d3c 100644
--- a/flang/include/flang/Parser/char-block.h
+++ b/flang/include/flang/Parser/char-block.h
@@ -150,7 +150,12 @@ class CharBlock {
int Compare(const char *that) const {
std::size_t bytes{size()};
- if (int cmp{std::strncmp(begin(), that, bytes)}) {
+ // strncmp is undefined if either pointer is null.
+ if (!bytes) {
+ return that == nullptr ? 0 : -1;
+ } else if (!that) {
+ return 1;
+ } else if (int cmp{std::strncmp(begin(), that, bytes)}) {
return cmp;
}
return that[bytes] == '\0' ? 0 : -1;
More information about the flang-commits
mailing list