c - 除以零会导致崩溃

标签 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++;
    }
}

最佳答案

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

C11 §6.5.5 Multiplicative operators

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.

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

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

或使用短路:

b && (c = a / b);
    

关于c - 除以零会导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19807123/

相关文章:

c - PADDD 指令的操作数

c++ - BIO 不会刷新 OpenSSL 中的数据

c - 基本 XML 解析器

c - 拆分字符串并显示它

输入后忽略回车键的C代码

c - xTicksToWait = portMAX_DELAY时,xQueueReceive会失败吗?

c - C 中的通用函数指针

c - 在 C 编程中将用户输入写入文件

iphone - 我如何构建这个静态 C 库以与 iPhone 一起使用

c++ - 将静态 Qt 库链接到 C 程序