在执行这段代码时,在函数末尾抛出以下错误
“运行时检查失败 #2 - 变量‘path’周围的堆栈已损坏”
TCHAR path[1024]={0};
GetTempPathW((sizeof(path)) - 1, path);
我知道声明中的变量“path”将分配 2048 字节。
在执行时,'path' 被填充了将近 32 个字节。但它将 0 设置为 2048 的其余部分(初始化时已经为 0)以及额外的 2044 字节。
(即)额外的 2044 字节被设置为 0。(它不应该访问)
谁能告诉我为什么会这样?
来自此处的文档:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992(v=vs.85).aspx
nBufferLength [in]
The size of the string buffer identified by lpBuffer, in TCHARs.
考虑这样的事情:
// buffer size in TCHARS
static constexpr DWORD buffer_size = MAX_PATH+1;
// make enough space, regardless of the size of a TCHAR
TCHAR buffer[buffer_size];
// communicate buffer length in terms of numbers of TCHARS
auto path_len = GetTempPath(buffer_size, buffer);
// check path_len for 0 - that would indicate an error
或者如果你愿意,
TCHAR buffer[MAX_PATH + 1];
// communicate buffer length in terms of numbers of TCHARS
auto path_len = GetTempPath(std::extent<decltype(buffer)>::value,
buffer);
// check path_len for 0 - that would indicate an error