-2

这将创建一个尝试除以零的错误,如果该错误未被语言的错误处理功能捕获,则可能会出现意外结果:

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++;
    }
}
4

2 回答 2

6

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

C11 §6.5.5 乘法运算符

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

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

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

或使用短路:

b && (c = a / b);
    
于 2013-11-06T08:28:30.460 回答
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 语言中除以零时崩溃是程序的预期行为。

于 2013-11-06T08:46:07.760 回答