[flang-commits] [flang] [flang] Avoid forming a reference from null pointer (PR #84787)

Krzysztof Parzyszek via flang-commits flang-commits at lists.llvm.org
Mon Mar 11 09:42:19 PDT 2024


https://github.com/kparzysz updated https://github.com/llvm/llvm-project/pull/84787

>From c15f70deb8cd26690e42fc9c59b0212247dcc10e Mon Sep 17 00:00:00 2001
From: Krzysztof Parzyszek <Krzysztof.Parzyszek at amd.com>
Date: Mon, 11 Mar 2024 10:24:51 -0500
Subject: [PATCH 1/2] [flang] Avoid forming a reference from null pointer

Doing so is an undefined behavior.

This was detected by the undefined behavior sanitizer.
---
 flang/lib/Parser/token-sequence.cpp | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/flang/lib/Parser/token-sequence.cpp b/flang/lib/Parser/token-sequence.cpp
index c5a630c471d16e..a53205b35f0761 100644
--- a/flang/lib/Parser/token-sequence.cpp
+++ b/flang/lib/Parser/token-sequence.cpp
@@ -136,7 +136,10 @@ void TokenSequence::Put(
 }
 
 void TokenSequence::Put(const CharBlock &t, Provenance provenance) {
-  Put(&t[0], t.size(), provenance);
+  // Avoid t[0] if t is empty: it would create a reference to nullptr,
+  // which is UB.
+  const char *addr = t.size() ? &t[0] : nullptr;
+  Put(addr, t.size(), provenance);
 }
 
 void TokenSequence::Put(const std::string &s, Provenance provenance) {

>From 25434183cb6807f07a6b59d98ffaaf150e30ce06 Mon Sep 17 00:00:00 2001
From: Krzysztof Parzyszek <Krzysztof.Parzyszek at amd.com>
Date: Mon, 11 Mar 2024 11:41:52 -0500
Subject: [PATCH 2/2] Use {} in initializer

---
 flang/lib/Parser/token-sequence.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/flang/lib/Parser/token-sequence.cpp b/flang/lib/Parser/token-sequence.cpp
index a53205b35f0761..799d13a423660c 100644
--- a/flang/lib/Parser/token-sequence.cpp
+++ b/flang/lib/Parser/token-sequence.cpp
@@ -138,7 +138,7 @@ void TokenSequence::Put(
 void TokenSequence::Put(const CharBlock &t, Provenance provenance) {
   // Avoid t[0] if t is empty: it would create a reference to nullptr,
   // which is UB.
-  const char *addr = t.size() ? &t[0] : nullptr;
+  const char *addr{t.size() ? &t[0] : nullptr};
   Put(addr, t.size(), provenance);
 }
 



More information about the flang-commits mailing list