简体   繁体   English

静态代码分析工具报告的缓冲区溢出问题

[英]Buffer overrun issue reported by static code analysis tool

My piece of code:我的一段代码:

void temp(char *source)
{
    char dest[41];

    for(int i = 0; i < 20; i++)
    {
        sprintf(&dest[i*2], "%02x", (unsigned int)source[i]);
    }
}

When I run the static code analysis tool, I get the warning below:当我运行静态代码分析工具时,我收到以下警告:

On 19th iteration of the loop : This code could write past the end of the buffer pointed to by &dest[i * 2].在循环的第 19 次迭代中:此代码可以写入超过 &dest[i * 2] 指向的缓冲区的末尾。 &dest[i * 2] evaluates to [dest + 38]. &dest[i * 2] 计算结果为 [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. sprintf() 从 &dest[i * 2] 指向的缓冲区开头的偏移量 38 开始写入最多 9 个字节,其容量为 41 个字节。写入的字节数可能超过超出该偏移量的已分配字节数。 The overrun occurs in stack memory.溢出发生在堆栈内存中。

My question is: since in every loop iteration, we are only copying 2 bytes (considering size of unsigned int on the machine is 2 bytes) from source to destination, where is the possibility of copying 9 bytes on the last iteration?我的问题是:由于在每次循环迭代中,我们只从源到目标复制 2 个字节(考虑到机器上 unsigned int 的大小为 2 个字节),那么在最后一次迭代中复制 9 个字节的可能性在哪里?

char can be signed, and is so by default in x86 compilers. char可以被签名,在 x86 编译器中默认如此。 On my computer在我的电脑上

#include <stdio.h>

int main(void) {
    printf("%02x\n", (unsigned int)(char)128);
}

prints ffffff80 .打印ffffff80

What you want to do is use format "%02hhx" and argument (unsigned char)c .想要做的是使用格式"%02hhx"和参数(unsigned char)c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM