gpt4 book ai didi

c - 除以零会导致崩溃

转载 作者:行者123 更新时间:2023-11-30 19:55:31 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com