[PATCH] D98798: Produce warning for performing pointer arithmetic on a null pointer.

Richard Smith - zygoloid via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Wed May 12 12:06:51 PDT 2021


rsmith added inline comments.


================
Comment at: clang/test/Sema/pointer-addition.cpp:5-6
+  char *f = (char*)0;
+  f = (char*)((char*)0 - f); // expected-warning {{performing pointer arithmetic on a null pointer has undefined behavior}}
+  f = (char*)(f - (char*)0); // expected-warning {{performing pointer arithmetic on a null pointer has undefined behavior}}
+  f = (char*)((char*)0 - (char*)0); // valid in C++
----------------
These two warnings are wrong -- their claim about these expressions having undefined behavior is incorrect. We can't prove that `f` is not null (and in fact it is null here), so we should not be producing a warning that says the code has undefined behavior. If you want to warn in the cases where you can prove the other pointer is non-null, and say that that case has undefined behavior, that seems fine, but please fix the diagnostic message to be technically correct (eg, "computing difference of a null pointer and a non-null pointer has undefined behavior").

Perhaps a better approach would be to use the same logic to decide whether to warn in C and C++, but produce different warning text. For example, you could say "[...] has undefined behavior" in C, but in C++ just say "warning: performing pointer arithmetic on a null pointer" without making potentially-inaccurate claims about UB? The code is still *suspicious* in C++ even if it's not UB.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D98798/new/

https://reviews.llvm.org/D98798



More information about the cfe-commits mailing list