变量周围的堆栈'folderPath'已损坏
Stack around the variable 'folderPath' was corrupted
嗨,我正在使用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
(。
相关文章:
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么C中的通用链表中存储的数据已损坏
- gdb错误:Backtrace已停止:上一帧与此帧相同(堆栈已损坏?)
- 变量周围的堆栈'...'已损坏
- 运行时检查失败 #2 变量"A"周围的堆栈已损坏
- 两个垫子的 OpenCV 数据是相同的,但使用 Mat::at 检索时的值已损坏
- 运行时检查失败 #2 - 变量"e"周围的堆栈已损坏。发生
- 变量周围的堆栈'sortArray'已损坏
- 变量周围的堆栈'folderPath'已损坏
- 在为 iOS 构建 aws-sdk-cpp 时,cmake 上的 CXX 编译器错误已损坏
- 运行时检查失败 #2 - 变量周围的堆栈'...'已损坏
- AES-128 CFB-8解密的前16个字节已损坏
- 运行时检查失败 #2 - 变量"l1"周围的堆栈已损坏
- C++:此代码可以编译,但引发运行时检查失败 #2 - 围绕变量周围的堆栈'num'已损坏。发生
- 图像在本地主机上显示已损坏
- 检查工作正常的 CXX 编译器:/cygdrive/c/cygwin64/bin/clang++ -- 已损坏
- 数组变量周围的堆栈已损坏
- 运行时检查失败 - 变量周围的堆栈已损坏
- 串行端口的传入值有时已损坏或丢失
- 自定义异常中的消息已损坏