简体   繁体   中英

Why error C6386 buffer overrun with strsafe.h StringCch functions?

So I ran an Analyze in VS 2017 with my C++ code. It gives me a buffer overrun with the following:

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

When I step through the code, sTemp is "0123", with the 4th position of course being \\0.

When I run Analyze on the code, I get the C6386 error:

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

Why? I have also tried changing the array to 10 and the StringCchCopy to 5 and still the same error.

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.

The docs for StringCchCopy say that the second parameter must be the size of the destination buffer and that the destination buffer must be big enough to hold the source string. You're not checking the return code from the function but I suspect it will be STRSAFE_E_INSUFFICIENT_BUFFER, which means "The copy operation failed due to insufficient buffer space. The destination buffer contains a truncated, null-terminated version of the intended result. In situations where truncation is acceptable, this may not necessarily be seen as a failure condition."

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

I guess you're happy with, and expecting, the truncation, but the static analysis tool is seeing that your source string is longer than your destination buffer and triggering the warning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM