c++ - GetTempPath() 写入的内存是否比发送的内存多?

标签 c++ visual-studio-2013

<分区>

在执行这段代码时,在函数末尾抛出以下错误

“运行时检查失败 #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

关于c++ - GetTempPath() 写入的内存是否比发送的内存多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34926509/

相关文章:

c++ - 在 new 表达式中分配内存后是否评估初始值设定项?

C++ 打印动态字符串数组错误

c++ - 20 个问题游戏

c++ - 如何在链表中搜索和插入多个节点

c++ - 有没有办法延长 C++ 中临时对象的生命周期?

c++ - Mac OSX libc++ 缺少 std::uncaught_exceptions 符号

c++ - 以编程方式打开系统信息

visual-studio-2013 - Visual Studio 2013 - 慢速扩展或加载项 - 如何找到哪一个?

visual-studio - Visual Studio 2013 "Add View"对话框需要很长时间才能加载

c# - 在 Windows Phone 8 应用程序中添加 Font Awesome