首页 > 解决方案 > 为什么错误 C6386 缓冲区溢出 strsafe.h StringCch 函数?

问题描述

所以我用我的 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,但仍然出现相同的错误。

标签: c++winapitcharbuffer-overrunstrsafe

解决方案


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.


推荐阅读