【问题标题】:Stack around the variable 'folderPath' was corrupted变量“folderPath”周围的堆栈已损坏
【发布时间】:2018-08-23 21:21:26
【问题描述】:

您好,我正在使用 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;
}

是什么原因造成的?我该如何解决?

【问题讨论】:

  • 您放入folderPath的字符串从不会超过九个字符吗?也就是说,FILE_NAME 的长度永远不会超过六个字符吗?
  • 顺便问一下FILE_NAME是什么?请read about how to ask good questions,并学习如何创建Minimal, Complete, and Verifiable Example
  • #define FILE_NAME "app.exe" 和 folderPath 是磁盘的地址:将类似于 d:\\app.exe
  • 您的 folderPath 数组太小。 c:\app.exe 是 10 个字符,您还需要一个用于 nul 终止符。
  • 没有必要将答案编辑到问题中,问题应该只包含问题而不是答案。如果您对自己的问题有自己的答案,请将其添加为答案

标签: c++


【解决方案1】:

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

不幸的是,您似乎忘记了 C++ 中的 char 字符串实际上称为 null-terminated 字节字符串,而 null-terminator 也需要空间。

由于空终止符(字符'\0')没有空间,最后一次strcat 调用将超出folderPath 数组的范围,导致undefined behavior(以及您得到的错误)。

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

char folderPath[11];

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

由于您使用的是路径,我建议您使用 std::filesystem::path(如果您没有可用的 C++17,则使用 Boost filesystem path)。

【讨论】:

    猜你喜欢
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2012-11-08
    • 2019-09-04
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多