Static Code Analysis - Identify possible division by Zero

Asked

Viewed 150 times

4

Does anyone know / built some logic (rule) of static source code analysis (for Fxcop or Gendarme) that searches for possible gaps in the code that incur a division by zero?

That is, a logic that analyzes Assembly’s IL and critiques the first code, but not the second:

// (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;
   }
  • Code Contracts is neither fxcop nor Gendarme, but detects these kinds of things.

1 answer

3

Visual Studio can from the syntactic analysis and construction of IL discover a possible division by 0.

But this analysis does not assume the "state" of the program, that is, 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.

inserir a descrição da imagem aqui

To prevent this, simply create a method in a class that does this division and let you know when you are debugging your code..

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.