Skip to content

Commit d889a74

Browse files
[flang] Avoid UB in CharBlock Compare to C string (llvm#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.
1 parent 2837557 commit d889a74

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

flang/include/flang/Parser/char-block.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,12 @@ class CharBlock {
150150

151151
int Compare(const char *that) const {
152152
std::size_t bytes{size()};
153-
if (int cmp{std::strncmp(begin(), that, bytes)}) {
153+
// strncmp is undefined if either pointer is null.
154+
if (!bytes) {
155+
return that == nullptr ? 0 : -1;
156+
} else if (!that) {
157+
return 1;
158+
} else if (int cmp{std::strncmp(begin(), that, bytes)}) {
154159
return cmp;
155160
}
156161
return that[bytes] == '\0' ? 0 : -1;

0 commit comments

Comments
 (0)