Andrew Truckle
Andrew Truckle

Reputation: 19197

C6386 warning passing WCHAR param to StringCchCopy - how to resolve?

This code is giving me the following code analysis warning:

C6386 Buffer overrun while writing to m_NID.szTip.

bool CCenterCursorOnScreenDlg::SetTrayIconTipText()
{
    if (StringCchCopy(m_NID.szTip, sizeof(m_NID.szTip), m_strTrayIconTip) != S_OK)
        return FALSE;

    m_NID.uFlags |= NIF_TIP;

    return Shell_NotifyIcon(NIM_MODIFY, &m_NID);
}

The structure in question (m_NID is of type NOTIFYICONDATA). How can I resolve this warning?

Upvotes: 0

Views: 141

Answers (1)

Chuck Walbourn
Chuck Walbourn

Reputation: 41127

The C++17 std::size(m_NID.szTip) in <iterator> is a "modern C++" equivalent to the old sizeof(m_NID.szTip)/sizeof(m_NID.szTip[0]). For MSVC, this is supported by the Standard C++ Library even when in the default C++11/C++14 compile mode.

https://en.cppreference.com/w/cpp/iterator/size

With that said, strsafe.h is very much the first-generation old-school approach here. A better option is to use the "Safer CRT" functions which are already part of the Visual Studio runtime. You could instead just use srcpy_s or wcscpy_s both of which have C++ template forms that automatically determine the size of fixed-sized buffers.

If using MBCS:

    if (strcpy_s(m_NID.szTip, m_strTrayIconTip) != S_OK)

or using UNICODE:

    if (wcscpy_s(m_NID.szTip, m_strTrayIconTip) != S_OK)

Upvotes: 2

Related Questions