如何修复 Visual Studio 2019 警告 C26052?

How do I fix Visual Studio 2019 warning C26052?

我正在使用 Visual Studio 2019 在 C 中创建 .dll

我正在使用 _In_bytecount_ 来尽可能地防止缓冲区溢出。

pmReportCrash(
    _In_bytecount_(_wndTitleLength * 2) LPCWCH _wndTitle,
    _In_ size_t _wndTitleLength,
    _In_bytecount_(_wndMSGLength * 2) LPCWCH _wndMSG,
    _In_ size_t _wndMSGLength,
    _In_bytecount_(_wndDescLength * 2) LPCWCH _wndDesc,
    _In_ size_t _wndDescLength,
    _In_bytecount_(_wndRestartCommandLength * 2) LPCWCH _wndRestartCommand,
    _In_ size_t _wndRestartCommandLength,
    _In_bytecount_(_wndIconDirLength * 2) LPCWCH _wndIconDir,
    _In_ size_t _wndIconDirLength,
    _In_bytecount_(_wndImageDirLength * 2) LPCWCH _wndImageDir,
    _In_ size_t _wndImageDirLength
)

但是当我把我的宽字符作为参数传递给swprintf_s时:

(swprintf_s(wndMSGParam, _wndMSGLength + 5, L"/m \"%s\"", _wndMSG);)

它开始这样说:

Warning C26052

Potentially unconstrained access using expression '(LPCWCH)_wndMSG' Buffer _wndMSG is passed to function swprintf_s as unannotated parameter 4 None of the other parameters seem to be constrained by the buffer length

Buffer _wndMSG is a parameter to this function declared on line 13 Buffer is of length offset(_wndMSG)13 + 2*_wndMSGLength13 bytes [from annotation SAL_readableTo(byteCount(_wndMSGLength * 2)) at c:\users%userdir%\source\repos\api.postman.crashreporter\api.postman.crashreporter\postman.crash reporter.h(16)]

Values of variables: Pointer _wndMSG is at offset 0 bytes from the start of the buffer Pointer result.malloc is at offset offset(result.malloc)53a bytes from the start of result.malloc'53 _wndMSGLength = _wndMSGLength13 wndMSGParam = result.malloc

where offset(_wndMSG)13 == 0 _wndMSGLength13 >= 1 API.Postman.CrashReporter C:\Users%userdir%\source\repos\API.Postman.CrashReporter\API.Postman.CrashReporter\PostMan.Crash Reporter.c 54

是否可以修复此警告,或者如果我想摆脱它,是否需要抑制它?

这里有一些想法:

  • 这些参数似乎没有以 null 结尾,因此您应该使用 %.*s 指定要从 _wndMSG.
  • 读取的最大长度
  • swprintf_s 的大小参数应包括 space 作为空终止符。
  • C 标准指定 %s 的参数类型应该是指向 char 的指针,而不是 wchar_t。除非 Microsoft 有不同的约定,否则您应该使用 %ls 作为 LPCWCH 参数。

试试这个:

swprintf_s(wndMSGParam, _wndMSGLength + 6, L"/m \"%.*ls\"",
           (int)_wndMSGLength, _wndMSG);

备注:

  • %ls 需要一个指向 wchar_t 的指针,一个宽字符串,它被原封不动地复制到目标数组。

  • %.*ls 中的 .* 指定要从字符串参数复制的最大字符数作为字符串指针之前的 int 参数传递。如果这个最大数是一个常量(例如:10),它可以写成 %.10ls 而无需额外的参数。请注意,此 precision 字段不同于 width 字段,后者可以紧跟在 % 之后,作为十进制数或*,并指定用 spaces 填充输出的字符数。例如:

    wchar_t wbuf[20];
    swprintf_s(wbuf, sizeof wbuf, L"|%10.5ls|", L"1234567");
    

    wbuf.

    中生成字符串 | 12345|