[flang-commits] [flang] [flang] Avoid UB in CharBlock Compare to C string (PR #147329)

via flang-commits flang-commits at lists.llvm.org
Mon Jul 7 08:45:42 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-flang-parser

Author: David Spickett (DavidSpickett)

<details>
<summary>Changes</summary>

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.

---
Full diff: https://github.com/llvm/llvm-project/pull/147329.diff


1 Files Affected:

- (modified) flang/include/flang/Parser/char-block.h (+6-1) 


``````````diff
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;

``````````

</details>


https://github.com/llvm/llvm-project/pull/147329


More information about the flang-commits mailing list