全局静态常量变量什么时候被初始化?
我试图在网站上搜索这个问题,但没有确切地找到这个问题,尽管这个主题已经被讨论了很多...
我在 cpp 文件中有这个声明,而不是在任何函数中:
static const char* gText = "xxxxxxxxxxx";
虽然它有固定的大小,但我当我尝试将其复制到另一个 char* 变量时,从静态分析工具(Klocwork)收到警告 - 关于可能的越界违规:
char xText[32];
SecureZeroMemory(xText, 32);
memcpy(xText, gText, strlen(gText));
这是误报还是稍后初始化全局变量?
谢谢!
I tried to search the site for this question but didn't find this exactly, although this subject is being discussed a lot...
I have this declaration in a cpp file, not within any function:
static const char* gText = "xxxxxxxxxxx";
Although it has a fixed size, I get a warning from a static analysis tool (Klocwork) when I'm trying to copy it to another char* variable - about possible out of bounds violation:
char xText[32];
SecureZeroMemory(xText, 32);
memcpy(xText, gText, strlen(gText));
Is it a false positive or is the global variable being initialized later?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是误报。
strlen
可能被抽象为返回一个未知的正数,因此在分析模式memcpy(dest,src,strlen(src));
时,分析器不会意识到只要src
是格式正确的字符串,读取副本的一部分就是安全的。如果您使用
strcpy
,分析器可能会认为在这种情况下没问题。你有理由不这样做吗?函数strcpy
被认为是“不安全”的,但你的memcpy(..,src,strlen(src))
也非常不安全。编辑:另外,sellibitze 在评论中提出了一个非常好的观点:原始代码中的 const 属性仅适用于 gText 指向的字符,而不适用于 gText本身。
It is a false positive.
strlen
is probably abstracted as returning an unknown positive number, so that when analyzing the patternmemcpy(dest,src,strlen(src));
the analyzer does not realize that the reading part of the copy is safe as soon assrc
is a well-formed string.If you were using
strcpy
, the analyzer would probably conclude that it's okay in this case. Do you have a reason not to? The functionstrcpy
is considered "unsafe" but yourmemcpy(..,src,strlen(src))
is quite unsafe too.EDIT: Also, sellibitze raises a very good point in the comments: the
const
attribute in the original code only applies to the chars pointed bygText
and not togText
itself.我认为这不是误报。存在潜在风险,即有人可能会更改 gText 的长度,但没有意识到它不能超过 32 个字符。我肯定会在 memcpy 之前进行某种检查,以确保不会出现缓冲区溢出。
例如
,我还将用常量替换幻数 32。
I would argue it is not a false positive. There is a potential risk that somebody could come along and change the length of gText without realising that it cannot be over 32 characters. I would definitely put some sort of check in before the memcpy to make sure there cannot be a buffer overrun.
e.g.
Also I'd replace the magic number 32 with a constant.