When are global static const variables being initialized?
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!
It is a false positive. strlen
is probably abstracted as returning an unknown positive number, so that when analyzing the pattern memcpy(dest,src,strlen(src));
the analyzer does not realize that the reading part of the copy is safe as soon as src
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 function strcpy
is considered "unsafe" but your memcpy(..,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 by gText
and not to gText
itself.
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.
char xText[32];
SecureZeroMemory(xText, 32);
size_t lenToCopy = MIN(strlen(gText), 32);
memcpy(xText, gText, lenToCopy);
Also I'd replace the magic number 32 with a constant.
精彩评论