“除以零”会导致崩溃

时间:2013-11-06 08:24:58

标签: c

如果尝试除以零会产生错误,如果语言的错误处理功能未捕获到此错误,则可能会出现意外结果:

static void aspect_adjust_packed4444_scanline_c( uint8_t *output,
                                                 uint8_t *input, 
                                                 int width,
                                                 double pixel_aspect )
{
    double i;
    int prev_i = 0;
    int w = 0;

    pixel_aspect = 1.0 / pixel_aspect;

    for( i = 0.0; i < width; i += pixel_aspect )
    {
        uint8_t *curin = input + ((int) i)*4;

        if( !prev_i )
        {
                output[ 0 ] = curin[ 0 ];
                output[ 1 ] = curin[ 1 ];
                output[ 2 ] = curin[ 2 ];
                output[ 3 ] = curin[ 3 ];
        }
        else
        {
            int avg_a = 0;
            int avg_y = 0;
            int avg_cb = 0;
            int avg_cr = 0;
            int pos = prev_i * 4;
            int c = 0; /* assignment: Assigning: "c" = "0" */
            int j;

            for( j = prev_i; j <= (int) i; j++ )
            {
                avg_a += input[ pos++ ];
                avg_y += input[ pos++ ];
                avg_cb += input[ pos++ ];
                avg_cr += input[ pos++ ];
                c++;
            }
            output[ 0 ] = avg_a / c;  /* Division or modulo by zero */
            output[ 1 ] = avg_y / c;  /* Division or modulo by zero */
            output[ 2 ] = avg_cb / c; /* Division or modulo by zero */
            output[ 3 ] = avg_cr / c; /* Division or modulo by zero */
        }
        output += 4;
        prev_i = (int) i;
        w++;
    }
}

2 个答案:

答案 0 :(得分:6)

除以零会导致未定义的行为。

  

C11§6.5.5乘法运算符

     

/运算符的结果是第一个操作数除以第二个操作数的商; %运算符的结果是余数。 在两个操作中,如果第二个操作数的值为零,则行为未定义。

C中没有异常处理,您需要以某种方式自行保护:

if (b != 0)
    c = a / b;

或使用短路:

b && (c = a / b);

答案 1 :(得分:1)

在您的代码中,只有在未执行此循环时,c才为零。您可以检查条件,也可以用1初始化c。

 int c = 0; /* assignment: Assigning: "c" = 0 */
 int j;

 for( j = prev_i; j <= (int) i; j++ ) {
     avg_a += input[ pos++ ];
     avg_y += input[ pos++ ];
     avg_cb += input[ pos++ ];
     avg_cr += input[ pos++ ];
     c++;
 }
 output[ 0 ] = avg_a / c;  /* Division or modulo by zero */
 output[ 1 ] = avg_y / c;  /* Division or modulo by zero */
 output[ 2 ] = avg_cb / c; /* Division or modulo by zero */
 output[ 3 ] = avg_cr / c; /* Division or modulo by zero */

但是,理解程序的逻辑和意图更为重要。

程序在C中除以零时崩溃的预期行为。