Static Code Analysis - Identify possible division by Zero

4

Does anyone know / have built some static code analysis rule (for a FxCop or Gendarme ) that looks for possible loopholes in the code that incur a division by zero? / p>

That is, a logic that analyzes the IL of the assembly and criticizes the first code, but not the second one:

// (1) Poderá ocorrer erro de divisão por Zero - deve acusar no analisador
   int resultado = numerador / denominador;

// (2) Checkagem antes da divisão - omite crítica
   int resultado;
   if (denominador != 0) 
   {
       resultado = numerador / denominador;
   }
    
asked by anonymous 03.04.2014 / 22:15

1 answer

3

Visual Studio is able to parse from the IL parsing and construct a possible division by 0.

But this analysis does not assume the "state" of the program, ie it is possible to discover a division by zero assuming constant values, but not by a value that comes from a variable calculation for example.

To prevent this, you simply create a method in a class that makes this division and tells you when to debug your code.

class DivisionTest
{
    public static int Divide(int numerator, int denominator)
    {
        if (denominator == 0)
        {
            // You need check this :/
            Debugger.Break();
        }
        return numerator / denominator;
    }
}
    
16.05.2014 / 20:28