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

标签 c static-code-analysis buffer-overrun

我的一段代码:

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/

相关文章:

c - 一些子进程多次完成他们的工作

lint - Bazel 跳棋支持

security - slice 操作导致缓冲区溢出和用户密码泄露?

c - 为什么它返回错误?

c - 关闭 cuda c 中的线程

c++ - Visual Studio 2015 代码分析 C6386 缓冲区溢出警告

javascript - 是否有(静态)JavaScript 函数调用跟踪工具?

c++-cli - 使用 Marshal::GetFunctionPointerForDelegate 并从非托管代码调用回调会导致退出应用程序时缓冲区溢出

c++ - 哪些 C/C++ 函数最常被错误使用并可能导致缓冲区溢出?

c - Linux内核源码中遇到的深奥#define宏