https://gcc.gnu.org/bugzilla/show_bug.cgi?id=125812
Bug ID: 125812
Summary: null pointer safety and optimization
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: uecker at gcc dot gnu.org
Target Milestone: ---
If one wants to protect against null pointer dereferences, one can use
-fsanitize=null with -fsanitize-traps. But on platforms where null pointer
dereferences trap this seems unnecessary. Also -fdelete-null-pointer-checks
seems generally safe to use. There is an exception though, and this is when
indexing into a pointer.
int f1(int *p)
{
int i = p[5000];
if (!p)
return -1;
return i;
}
In this case, the null pointer check is removed (ok as there was a dereference
before), but without a sanitizer one might not get a trap if the offset is big
enough to land in allocated storage. What already works quite well is moving
the checks from the callee into the caller using [static] or the nonnull
attribute (and no inlining). But in the case of a variable index, the null
pointer check is stll not removed, which I think could be done, because
preserving it seems useless in terms of safety.
What is really missing is a way to get to the sweet spot, where one gets a
guaranteed trap but without adding unnecessary checks or impacting
optimization.
Examples: https://godbolt.org/z/P1WvejqTM