# CS.DBZ.GENERAL

Assigned zero constant value might be used in a division by zero

An attempt to do a division or modulo operation using zero as the divisor causes a runtime error. Division by zero defects often occur due to ineffective error handling or race conditions, and typically cause abnormal program termination. Before a value is used as the divisor of a division or modulo operation in C# code, it must be checked to confirm that it is not equal to zero.

The DBZ checkers look for instances in which a zero constant value is used as the divisor of a division or modulo operation.

The CS.DBZ.GENERAL checker flags situations in which a variable that has been assigned a zero constant value locally, or as the result of a function call, might subsequently be used explicitly or passed to a function that might use it as a divisor of a division or modulo operation, without checking it for the zero value.

## Vulnerability and risk

Integer division by zero usually results in the failure of the process or an exception. It can also result in the success of the operation, but gives an erroneous answer.

## Mitigation and prevention

Division by zero issues typically occur due to ineffective exception handling. To avoid this vulnerability, check for a zero value before using it as the divisor of a division or modulo operation.

## Vulnerable code example

Copy
```1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
`   namespace DBZ   {       class Program       {           static int Test1(int[] array, int size)           {               int sum = 0;               for (int i = 0; i < 3; ++i)               {                  sum += array[i];              }              return sum / size;          }          static void Main(string[] args)          {              int size = 0;              int[] arr = { 2, 3, 4 };              int mean = Test1(arr, size);         }      }  }````

Klocwork produces an issue report at line 18 indicating that 'size' might be used in a division by zero.

## Fixed code example

Copy
```1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
`   namespace DBZ   {       class Program       {           static int Test1(int[] array, int size)           {               if(size ==0)               {                   return 0;              }              int sum = 0;              for (int i = 0; i < 3; ++i)              {                  sum += array[i];              }              return sum / size;          }          static void Main(string[] args)          {              int size = 0;              int[] arr = { 2, 3, 4 };              int mean = Test1(arr, size);         }      }  }````

The issue from the vulnerable code example is fixed. The input variable 'size' is checked for a zero constant value in line 7 and prevents the division operation from occurring if the value is zero.

## Security training

Application security training materials provided by Secure Code Warrior.