组合 std::string 和 C 字符串会导致缓冲区溢出
Combining std::strings and C-Strings causes buffer overrun
我正在尝试创建一个函数,使在我的C++ WinAPI应用程序中组合C字符串和std::string
更容易一些。
因此,与其这样做:
TCHAR res[MAX_PATH];
_stprintf(res, _T("In functionX(): error occured where the variable values are %d, %u, %s, %c"), myInt, myUnsignedInt, myStr.c_str(), myChar);
MessageBox(NULL, res, _T("Error Occurred"), MB_OK);
我只需要这样做(这使得合并不同的字符串类型更容易一些,因为我不必在任何地方声明 TCHAR 数组):
tstring res = concat(_T("In functionX(): error occured with the variable values %d, %u, %s, %c"), myInt, myUnsignedInt, myStr.c_str(), myChar);
MessageBox(NULL, (LPTSTR)res.c_str(), _T("Error Occurred"), MB_OK);
我的问题:当我在参数格式中传递超过 1 个变量时,我的函数 concat(); 失败了,我不知道为什么?
// The following function call causes the error
tstring ou = concat(_T("In functionX(): Failed to create temp file - %s - %srn"), (LPTSTR)tempFileRootDir.c_str(), tempFile);
tstring WinFile::concat( TCHAR* strFormat, TCHAR* format, ... )
{
// tstring is either a std::string or std::wstring depending on whether unicode is used
// Post: Wrapper function to easily merge C++ strings with C Strings
va_list arguments;
va_start(arguments, format);
TCHAR res[MAX_PATH];
_stprintf(res, strFormat, format);
return tstring(res);
}
在 Microsoft Visual C++ 中运行函数时发生的错误是:
应用程序中发生缓冲区溢出.exe该应用程序具有 损坏了程序的内部状态。按中断以调试 程序或继续终止程序。
有关更多详细信息,请参阅帮助主题"如何调试缓冲区溢出" 问题'。
看起来你的 varargs 处理有点不对劲。 是的,通过写入固定大小的缓冲区,您正在请求堆栈溢出。
要更正第一个问题,您需要使用 varargs 接受版本的 printf。 对于第二个,您应该在打印前计数:
tstring WinFile::concat( TCHAR const * strFormat, ... )
{
va_list args;
// Determine how much space to reserve.
va_start(args, strFormat);
size_t msg_len=_vsctprintf(strFormat, args);
va_end(args);
// Reserve space on heap.
//
// "_vscprintf returns the number of characters that would be generated
// if the string pointed to by the list of arguments was printed ...
// [and] does not include the terminating null character."
//
// So we add space for a terminating null.
std::vector<TCHAR> writebuffer(1+msg_len);
// perform formatting
va_start(args, strFormat);
_vstprintf(&writebuffer[0], strFormat, args);
va_end(args);
// return a copy as a tstring.
return tstring(&writebuffer[0], &writebuffer[msg_len]);
}
相关文章:
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么我在leetcode上收到AddressSanitizer:地址0x602000000058上的堆缓冲区溢出错误
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 使用 strcat 获取缓冲区溢出错误
- LeetCode 1:两和 - 地址清理器:堆缓冲区溢出地址
- 使用向量的缓冲区溢出
- 重新增长阵列时出错:写入时缓冲区溢出
- Leetcode 1366:堆缓冲区溢出
- 缓冲区溢出 - 数组索引越界(严重)
- C++二维矢量导致缓冲区溢出
- 缓冲区溢出怎么会成为黑客的攻击
- 如何防止缓冲区溢出
- 应该如何读取堆缓冲区溢出错误消息?
- 自动截断和 null 终止缓冲区溢出中的字符串缓冲区
- 如果用户输入两个或多个由空格分隔的字符串C++如何防止缓冲区溢出?
- 我正在尝试使用回溯来解决 N queen 问题,但在编译时它会给出运行时错误(动态堆栈缓冲区溢出)
- 为什么 LeetCode 给出错误:地址清理器:堆缓冲区溢出
- 为什么错误 C6386 缓冲区溢出与 strsafe.h 字符串 Cch 函数
- 读取文件时字符缓冲区溢出
- C 文本写入随机数据.是否有缓冲区溢出