Search code examples
mathcudadivide-by-zero

Undefined division in CUDA kernel - Any ideas?


While writing a CUDA kernel just now, I had occasion to test the result of the following code:

unsigned char temp1 = 0x00;
unsigned char temp2 = 0x00;
unsigned char temp3 = temp1/temp2;

printf("%02X", temp3);`

This code prints "0xFF". I am extremely perplexed by this, can anyone offer an explanation?


Solution

  • The result of an integer division by zero is undefined according to the C/C++ standards. See C99 section 6.5.5, for example:

    The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined

    In the case of division by zero, the integer division operators on NVIDIA GPUs return a result with all bits set to 1. This may be for compatibility with DirectX. The same applies to a modulo operator where the divisor is zero. You may observe different results when all operands are literal constants, as those cases are probably handled by the compiler optimizer at compile time.

    In any event CUDA programmers should definitely treat these results as implementation artifacts, as one cannot rely on undefined behavior in any way at any time.