return value of malloc

Hi list,

Is there a simple way for Clang Static Analyzer to assume that malloc-family functions always return non-null values?
Otherwise, it would be appreciated if you point which part I should change to do that.



As far as I know, the analyzer is relatively conservative with such functions, and only assumes that the returned value may be null, when it is checked in the code, e.g.

int a = (int)malloc(sizeof(int));
*a = 5; // The analyzer won’t assume that a may be null
if (a) {} // Now the analyzer will assume that it may be null as well.

Is your code structured like that?


  • Artem, am I correct here?

That's right, the analyzer would only assume that a null value is possible after the code has explicitly checked for that. If you believe that it can't be null in the first place, why check?

If you really want to prevent the Analyzer from exploring the null path even after an explicit check, go to MallocChecker::MallocMemAux() and do something like

 State = State\->assume\(RetVal, true\);

I guess we could have a flag for that, as well as for the opposite belief of "malloc should always be checked before use" (i.e., assume it can be null even without the explicit check in the code), but i'm not in favor of either of these two.

Also, @Kristóf: in your example the Analyzer cannot assume at line 3 `if (a) {}` that 'a' is equal to null. Because if it did, it would imply that a null dereference has already happened on line 2 on this execution path. This doesn't happen because on line 2 it not only doesn't assume that 'a' can be null, it in fact actively assumes that 'a' is not null. Most checkers should work this way: if the non-buggy state is feasible, transition into the non-buggy state and drop the buggy state entirely.