我的一段代码:
void temp(char *source)
{
char dest[41];
for(int i = 0; i < 20; i++)
{
sprintf(&dest[i*2], "%02x", (unsigned int)source[i]);
}
}
当我运行静态代码分析工具时,我收到以下警告:
On 19th iteration of the loop : This code could write past the end of the buffer pointed to by &dest[i * 2]. &dest[i * 2] evaluates to [dest + 38]. sprintf() writes up to 9 bytes starting at offset 38 from the beginning of the buffer pointed to by &dest[i * 2], whose capacity is 41 bytes.The number of bytes written could exceed the number of allocated bytes beyond that offset. The overrun occurs in stack memory.
我的问题是:由于在每次循环迭代中,我们仅从源到目标复制 2 个字节(考虑到机器上 unsigned int 的大小为 2 个字节),那么在最后一次迭代中复制 9 个字节的可能性在哪里?
最佳答案
char
可以进行签名,并且在 x86 编译器中默认如此。在我的电脑上
#include <stdio.h>
int main(void) {
printf("%02x\n", (unsigned int)(char)128);
}
打印ffffff80
。
您想要做的是使用格式“%02hhx”
和参数(unsigned char)c
。
关于c - 静态代码分析工具报告的缓冲区溢出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59393480/