When compiling with Microsoft's /analyze static analysis command line option for cl.exe, I get the warning
warning C6011: Dereferencing NULL pointer 'foo'
on a code path that calls a trivial function that guarantees that foo is not NULL where the analyzer thinks it can be.
The trivial function:
bool check_ptr(void* ptr)
{
if (!ptr)
{
// The original does more things here, but
// the repro is valid even without that.
return false;
}
return true;
}
The calling site:
foo_t* foo = lookup_foo(id);
if (!check_ptr(foo))
return;
foo->bar = 4711; // warning C6011: Dereferencing NULL pointer 'foo'
The analyzer is really bad at seeing through function calls, even trivial ones. If check_ptr is reduced to
bool check_ptr(void* ptr)
{
return !!ptr;
}
then the analyzer can deduce that foo cannot be NULL when dereferenced, but that's not an option. The checker function is there for a reason.
So, I assume that there is an ungodly SAL annotation combination that can be applied to check_ptr to convince the analyzer that if it returns true, then the foo argument is not NULL.
Is there such a SAL annotation?
EDIT: I found a SAL solution and added it as a separate answer https://stackoverflow.com/a/74459650/6345
It's not exactly using SAL, but a generic answer that should work all the time: instead of returning bool, you might take two lambdas: one for then, one for else:
You could even have
lookup_foo()andif_check_ptr()in one call.