最近项目在运行时出现"Buffer too small"

时间:2022-10-21 20:21:37
int __cdecl _vsprintf_s_l (
        char *string,
        size_t sizeInBytes,
        const char *format,
        _locale_t plocinfo,
        va_list ap
        )
{
    int retvalue = -1;


    /* validation section */
    _VALIDATE_RETURN(format != NULL, EINVAL, -1);
    _VALIDATE_RETURN(string != NULL && sizeInBytes > 0, EINVAL, -1);


    retvalue = _vsnprintf_helper(_output_s_l, string, sizeInBytes, format, plocinfo, ap);
    if (retvalue < 0)
    {
        string[0] = 0;
        _SECURECRT__FILL_STRING(string, sizeInBytes, 1);
    }
    if (retvalue == -2)
    {
        _VALIDATE_RETURN(("Buffer too small", 0), ERANGE, -1);		// 异常弹框处
    }
    if (retvalue >= 0)
    {
        _SECURECRT__FILL_STRING(string, sizeInBytes, retvalue + 1);
    }


    return retvalue;
}


开始以为我程序中的wsprintf和sprintf出的问题,后来上网搜了一下,才发现原来是使用CString时用到Format这个函数,参数直接给字符串数组时,有几率发生这种运行时错误,现先用CString赋值,再作参数,如:

char sz_SysDirPath[MAXBYTE] = "";
				GetSystemDirectory(sz_SysDirPath,MAXBYTE);

				CString csSysDirPath = sz_SysDirPath;

				CString cs_DriverPath;
				cs_DriverPath.Format("%s\\memory.sys",csSysDirPath.GetBuffer(0));