阔char数组的一个疑问

宽char数组的一个疑问
// 如果工作目录为空,则自传一个
if (pConvertParam->pszWorkingDir != NULL && _wcslen(pConvertParam->pszWorkingDir) > 0)
{
_wcscpy_s(m_szWorkingDir, _wcslen(pConvertParam->pszWorkingDir)+1, pConvertParam->pszWorkingDir);
}
else
{
CString strTmp;
GetTMPPath(strTmp);
_wcscpy_s(m_szWorkingDir, strTmp.GetLength()+1, strTmp.GetBuffer());
}

  m_szWorkingDir是wchar数组,红色部分为什么要+1?不加的话会有什么错误码?

------解决方案--------------------
_wcscpy_s其实就是宽字符版本的strncpy。

第二个参数在这里就是说m_szWorkngDir这个buffer最多可以容纳多少个字符的意思,当然是要容纳下整个字符串外加一个结束符了,所以是+1。 不过这个函数不core掉的前提是你的m_szWorkingDir的确有strTmp.GetLength()+1这么长,否则就非法内存操作了噢。
------解决方案--------------------
The strcpy_s function copies the contents in the address of strSource, including the terminating null character, to the location specified by strDestination. The destination string must be large enough to hold the source string, including the terminating null character. The behavior of strcpy_s is undefined if the source and destination strings overlap.

wcscpy_s and _mbscpy_s are wide-character and multibyte-character versions of strcpy_s respectively. The arguments and return value of wcscpy_s are wide character strings; those of _mbscpy_s are multibyte character strings. These three functions behave identically otherwise.

If strDestination or strSource is a null pointer, or if the destination string is too small, the invalid parameter handler is invoked as described in Parameter Validation. If execution is allowed to continue, these functions return EINVAL and set errno to EINVAL.

Upon successful execution, the destination string will always be null terminated.

In C++, using these functions is simplified by template overloads; the overloads can infer buffer length automatically (eliminating the need to specify a size argument) and they can automatically replace older, non-secure functions with their newer, secure counterparts. For more information, see Secure Template Overloads.
------解决方案--------------------
具体要看m_szWorkingDir是否足够能放下strTmp,包括结束符。如果strTmp长度大于m_szWorkingDir,则VS2010下异常抛出。