|
| 1 | +/** |
| 2 | + * @name Guarded Free |
| 3 | + * @description NULL-condition guards before function calls to the memory-deallocation |
| 4 | + * function free(3) are unnecessary, because passing NULL to free(3) is a no-op. |
| 5 | + * @kind problem |
| 6 | + * @problem.severity recommendation |
| 7 | + * @precision very-high |
| 8 | + * @id cpp/guarded-free |
| 9 | + * @tags maintainability |
| 10 | + * readability |
| 11 | + * experimental |
| 12 | + */ |
| 13 | + |
| 14 | +import cpp |
| 15 | + |
| 16 | +class FreeCall extends FunctionCall { |
| 17 | + FreeCall() { this.getTarget().hasName("free") } |
| 18 | +} |
| 19 | + |
| 20 | +from IfStmt stmt, FreeCall fc, Variable v |
| 21 | +where |
| 22 | + stmt.getThen() = fc.getEnclosingStmt() and |
| 23 | + ( |
| 24 | + stmt.getCondition() = v.getAnAccess() and |
| 25 | + fc.getArgument(0) = v.getAnAccess() |
| 26 | + or |
| 27 | + exists(PointerDereferenceExpr cond, PointerDereferenceExpr arg | |
| 28 | + fc.getArgument(0) = arg and |
| 29 | + stmt.getCondition() = cond and |
| 30 | + cond.getOperand+() = v.getAnAccess() and |
| 31 | + arg.getOperand+() = v.getAnAccess() |
| 32 | + ) |
| 33 | + or |
| 34 | + exists(ArrayExpr cond, ArrayExpr arg | |
| 35 | + fc.getArgument(0) = arg and |
| 36 | + stmt.getCondition() = cond and |
| 37 | + cond.getArrayBase+() = v.getAnAccess() and |
| 38 | + arg.getArrayBase+() = v.getAnAccess() |
| 39 | + ) |
| 40 | + or |
| 41 | + exists(NEExpr eq | |
| 42 | + fc.getArgument(0) = v.getAnAccess() and |
| 43 | + stmt.getCondition() = eq and |
| 44 | + eq.getAnOperand() = v.getAnAccess() and |
| 45 | + eq.getAnOperand().getValue() = "0" |
| 46 | + ) |
| 47 | + ) |
| 48 | +select stmt, "unnecessary NULL check before call to $@", fc, "free" |
0 commit comments