1

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.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
JeffR
  • 765
  • 2
  • 8
  • 23
  • 1
    It's not an error, but a warning – Neijwiert Jul 10 '19 at 12:46
  • Presumably because the static analyse cannot verify the size of the buffer. Declare it as `TCHAR sTemp[5]` instead. Also, give up on `TCHAR` unless you need to support Windows 98. – David Heffernan Jul 10 '19 at 12:47
  • Yeah, just habit of TCHAR. All unicode. Wonder why it can't verify the size? – JeffR Jul 10 '19 at 12:51
  • Presumably because the buffer is dynamically allocated and the tool doesn't perform data flow analysis. But why are you punishing yourself anyway? Just use `std::wstring`. – David Heffernan Jul 10 '19 at 13:17

2 Answers2

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.

IInspectable
  • 46,945
  • 8
  • 85
  • 181
-1

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://learn.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.

Chris Long
  • 1,299
  • 7
  • 15
  • I'm sceptical of this. The warning message seems to indicate that the tool can't verify the size of the buffer. *the writable size is 'unsigned int' bytes* would indicate that the tool has no idea of the size of the buffer. – David Heffernan Jul 10 '19 at 13:16