0

所以我用我的 C++ 代码在 VS 2017 中运行了分析。它给了我一个缓冲区溢出,如下所示:

TCHAR *sTemp = new TCHAR[5]();
if (sTemp)
    StringCchCopy(sTemp, 5, L"0123456789");

当我单步执行代码时,sTemp 是“0123”,第 4 位当然是 \0。

当我对代码运行分析时,我收到 C6386 错误:

Warning C6386   Buffer overrun while writing to 'sTemp':  the writable size is 'unsigned int' bytes, but '10' bytes might be written.

为什么?我还尝试将数组更改为 10,将 StringCchCopy 更改为 5,但仍然出现相同的错误。

4

2 回答 2

0

The warning refers to the fact, that the source string will not ever fit inside the destination. The source string has a length of 10, the destination a size of 5 code units. It's not relevant at all, that the static analyzer cannot determine the size of the dynamically allocated destination array.

If it were, and it would discover a mismatch between the actual size and the size you claimed, it would raise an error, not a warning.

于 2019-07-10T14:58:40.030 回答
-1

StringCchCopy 的文档说第二个参数必须是目标缓冲区的大小,并且目标缓冲区必须足够大以容纳源字符串。您没有检查函数的返回代码,但我怀疑它将是 STRSAFE_E_INSUFFICIENT_BUFFER,这意味着“由于缓冲区空间不足,复制操作失败。目标缓冲区包含预期结果的截断、以空结尾的版本。在某些情况下在可以接受截断的情况下,这可能不一定被视为失败条件。”

https://docs.microsoft.com/en-us/windows/win32/api/strsafe/nf-strsafe-stringcchcopyw

我猜您对截断感到满意并期待截断,但静态分析工具发现您的源字符串比目标缓冲区长并触发警告。

于 2019-07-10T12:55:19.587 回答