gpt4 book ai didi

python - snprintf 仍然提示缓冲区溢出

转载 作者:行者123 更新时间:2023-12-02 15:43:12 25 4
gpt4 key购买 nike

当我通过 Fortify 分析器工具之一运行我的代码时,它提示 snprintf 说“格式字符串参数没有正确限制函数可以写入的数据量”

我了解 snprintf 不应导致缓冲区溢出。但仍然是为什么该工具会引发此提示。有人可以帮忙吗?

最佳答案

I understand snprintf should not result in buffer overflow. But still why the tool raises this complain. Can anyone please help?

我经常看到分析工具的提示非常真实,但该工具指出了错误的罪魁祸首。


代码至少有这个弱点

timebuf[] 中的潜在垃圾

char timebuf[20];
// Enough space?
strftime(timebuf, sizeof(timebuf),"%Y-%m-%d %H:%M:%S", adjustedtime);

作为 adjustedtime->tm_year,一个 int,可能具有 -2147483648 ... 2147483647 范围内的值,大小超过 20需要。

避免尺码不足。推荐:

#define INT_TEXT_LENGTH_MAX 11
char timebuf[6*INT_TEXT_LENGTH_MAX + sizeof "%Y-%m-%d %H:%M:%S"];

进一步,如果缓冲区不够大,则:

If the total number of resulting characters including the terminating null character is not more than maxsize, the strftime function returns the number of characters placed into the array pointed to by s not including the terminating null character. Otherwise, zero is returned and the contents ofthe array are indeterminate. C17dr § 7.27.3.5 Library 8

因此,分析工具可以假定timebuf[]任何 内容,包括未检查的strftime() 之后的非字符串。这很容易破坏 snprintf(gendata, sizeof(gendata), "%s", timebuf); 因为 "%s" 需要一个 stringtimebuf[] 不保证是。 snprintf(gendata, sizeof(gendata), ... 中的 sizeof(gendata) 不足以阻止未终止的 timebuf[] 的 UB >.

更好的代码也会检查大小。

struct tm *adjustedtime = localtime(&t);
if (adjustedtime == NULL) {
Handle_Error();
}
if (strftime(timebuf, sizeof(timebuf),"%Y-%m-%d %H:%M:%S", adjustedtime) == 0) {
Handle_Error();
}

现在我们可以继续 snprintf() 代码。

关于python - snprintf 仍然提示缓冲区溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75402783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com