I'm dealing with old code, that has lots of lines like:
EST_Item_Content *contents() const { return (this == 0) ? 0 : p_contents;}
When compiling such functions, clang warns:
warning: 'this' pointer cannot be null in well-defined C++ code; comparison may be assumed to always evaluate to false [-Wtautological-undefined-compare]
The warning is correct, but the code is not "well-defined" and the checks are essential...
Yet, it is evident, that the check is being optimized away and the code crashes at run-time. Here is the sample gdb-session:
Program terminated with signal SIGSEGV, Segmentation fault.
Address not mapped to object.
#0 EST_Item::contents (this=0x0) at ../include/ling_class/EST_Item.h:238
238 EST_Item_Content *contents() const { return (this == 0) ? 0 : p_contents;}
(gdb) p this
$1 = (const EST_Item *) 0x0
When built without -O2
, the checks remain there, and the code works as it has for years.
How do I tell clang to not optimize away these checks, which it considers redundant? There is got to be some -f
-flag for it...
The flag is -fno-delete-null-pointer-checks
. It is specific to such checks of this
pointers against null though. It doesn't apply to all tautological comparisons.