变量周围的堆栈'folderPath'已损坏

Stack around the variable 'folderPath' was corrupted

本文关键字:folderPath 已损坏 周围 变量 堆栈      更新时间:2023-10-16

嗨,我正在使用Visual Studio并尝试制作一个将自身复制到磁盘的程序,当我运行时它就是这样做的,但是后来我收到消息:

"*Run-Time Check Failure #2 - Stack around the variable 'folderPath' was corrupted*."

代码如下:

void copyToDrive(char driveLetter) {
char folderPath[10] = { driveLetter };
strcat(folderPath, ":\");
strcat(folderPath, FILE_NAME);
char filename[MAX_PATH];
DWORD size = GetModuleFileNameA(NULL, filename, MAX_PATH);
std::ifstream src(filename, std::ios::binary);
std::ofstream dest(folderPath, std::ios::binary);
dest << src.rdbuf();
return;
}

是什么原因造成的?我该如何解决这个问题?

字符串"app.exe"长度为七个字符。这意味着您构造的字符串的总长度将为十个字符。

不幸的是,您似乎忘记了C++中的char字符串实际上称为以 null 结尾的字节字符串,并且null 终止符也需要空格。

由于没有空间容纳 null 终止符(字符''(,因此最后一个strcat调用将写出folderPath数组的边界,从而导致未定义的行为(以及您得到的错误(。

简单的解决方案是向数组添加一个元素,以便为终止符腾出空间:

char folderPath[11];

更正确的解决方案是改用std::string,而不必担心长度。

由于您正在使用路径,因此我建议您使用std::filesystem::path(如果您没有可用的 C++17,则使用 Boost 文件系统path(。