我已经阅读了很多关于Visual Studio Code分析警告C6386的内容,但是无法弄清楚我的代码中特定的问题。我将其简化为以下小程序:
unsigned int nNumItems = 0;
int main()
{
int *nWords=nullptr;
unsigned int nTotal;
nTotal = 3 + 2 * nNumItems;
nWords = new int[nTotal];
nWords[0] = 1;
nWords[1] = 2; // this is line 18, warning C6386
delete[] nWords;
return 0;
}
Analyze->Run Code Analysis->On Solution会出现以下警告:
file.cpp(18): warning C6386:在写入“nWords”时缓冲区溢出:可写大小为'nTotal*4'字节,但可能会写入'8'字节。
这个警告是真实的吗?如果我将全局变量移至本地,则此警告将消失!
int main()
{
unsigned int nNumItems = 0;
...
}
但是在完整的代码中,这是一个成员变量,因此我无法这样做。
同样地,如果我将nTotal的定义移到“new int”中,我也可以消除警告:
nWords = new int[3 + 2 * nNumItems];
但我无法这样做,因为在完整代码的其他地方引用了nWords。
这只是Visual Studio静态代码分析器的问题,还是这段代码存在合法问题?
std::vector<int>
代替。 - NathanOlivernNumItems = 0xffffffff
,那么就会发生缓冲区溢出。但这并不改变警告在这种情况下是荒谬的事实。 - Mysticial