为什么使用round()而不是floor()可能会导致C中的bug/(程序错误)



我正在调试一些需要调试和修复错误或可能的错误的代码。在其中一个例子中,有人说round()可能会导致错误,并用floor()修复了它。然而,我不太明白为什么。

有人能举个例子吗?

for (unsigned y = 0; y < round(factor * img->size_y); y++) { // round changed to floor
for (unsigned x = 0; x < round(factor * img->size_x); x++) { // round changed to floor
/* Calculate the location of the pixel in the old image */
unsigned nearest_x = x / factor;
unsigned nearest_y = y / factor;
/* Store the pixel */
image_data_new[y][x] = image_data[nearest_y][nearest_x];
}
}

在上面的代码中,round()floor()取代,以避免可能的攻击或错误。

初始化代码:

struct pixel(*image_data_new)[new_width] =
(struct pixel(*)[new_width])new_img->px;

其中new_width:

unsigned new_width = (unsigned)(img->size_x * factor);
double factor = atof(argv[3]);

您的维度似乎是

unsigned new_width = (unsigned)(img->size_x * factor);

在这种情况下,强制转换为integer具有与floor相同的效果。

现在您正在使用

for (unsigned x = 0; x < round(factor * img->size_x); x++) 

这真的是在寻找麻烦,因为如果小数点四舍五入的结果高于.5(并且可能溢出缓冲区(,round将产生一个可能大于new_width的值。只需使用之前计算的值:

for (unsigned x = 0; x < new_width; x++) 

如果round四舍五入,则nearest_y可以等于img->size_y,后者大于用于索引的数组的维度。

相关内容

最新更新