我有一个关于图像特征的函数,当我 malloc 一个缓冲区时(通过读取 header 的缓冲区大小)。 强化报告在这里告诉我“整数溢出”。 但是,无论我是修复代码还是检查颜色值, 强化报告仍然告诉我“整数溢出”
有人有什么建议吗?
代码:
int ReadInt()
{
int rnt=0;
rnt = getc(xxx);
rnt += (getc(xxx)<<8);
rnt += (getc(xxx)<<16);
rnt += (getc(xxx)<<24);
return rnt;
}
int image()
{
....
image->header_size=ReadInt();
image->width=ReadInt();
image->height=ReadInt();
....
image->colors =ReadInt();
int unit_size = 0;
unit_size = sizeof(unsigned int);
unsigned int malloc_size = 0;
if (image->colors > 0 &&
image->colors < (1024 * 1024 * 128) &&
unit_size > 0 &&
unit_size <= 8)
{
malloc_size = (image->colors * unit_size);
image->palette = (unsigned int *)malloc( malloc_size );
}
....
return 0;
}
强报告:
Abstract: The function image() in xzy.cpp does not account for
integer overflow, which can result in a logic error or a buffer overflow.
Source: _IO_getc()
59 rnt += (getc(xxx)<<8);
60 rnt += (getc(xxx)<<16);
61 rnt += (getc(xxx)<<24);
62 return rnt;
Sink: malloc()
242 malloc_size = (image->colors * unit_size);
243 image->palette = (unsigned int *)malloc( malloc_size );
244
最佳答案
左移 int
任何时候将“1”位移入符号位时都有可能出现未定义行为 (UB)。
这可能发生在任意 int
上中的值 some_int << 8
.
getc()
返回 unsigned char
中的值范围或负数 EOF
.左移 a EOF
是UB。使用 128 << 24
左移一个值,例如 128|是UB。
而是从 getc()
中累积非负值使用无符号数学。
建议更改函数签名以适应文件结尾/输入错误。
#include <stdbool.h>
#include <limits.h>
// return true on success
bool ReadInt(int *dest) {
unsigned urnt = 0;
for (unsigned shift = 0; shift < sizeof urnt * CHAR_BIT; shift += CHAR_BIT) {
int ch = getc(xxx);
if (ch == EOF) {
return false;
}
urnt |= ((unsigned) ch) << shift;
}
*dest = (int) urnt;
return true;
}
(int) urnt
转换调用“实现定义的或实现定义的信号被引发”,这通常是预期的功能:urnt
中的值以上INT_MAX
“环绕”。
或者,迂腐的代码可以使用:
if (urnt > INT_MAX) {
*dest = (int) urnt;
} else {
*dest = ((int) (urnt - INT_MAX - 1)) - INT_MAX - 1;
}
image->colors * unit_size
的改进.
//int unit_size = 0;
// unit_size = sizeof(unsigned int);
size_t unit_size = sizeof(unsigned int);
// unsigned int malloc_size = 0;
if (image->colors > 0 &&
// image->colors < (1024 * 1024 * 128) &&
image->colors < ((size_t)1024 * 1024 * 128) &&
unit_size > 0 &&
unit_size <= 8)
{
size_t malloc_size = (size_t) image->colors * unit_size;
// image->palette = (unsigned int *)malloc( malloc_size );
image->palette = malloc(malloc_size);
1024 * 1024 * 128
INT_MAX < 134217728
时出现问题(28 位 int
)。
参见 There are reasons not to use 1000 * 1000 * 1000
关于c - 如何解决强化报告中的整数溢出? (C代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53001194/