c++ - 如何修复 C++ 中的 'Heap has been corrupted ' 错误?

标签 c++ arrays heap-memory heap-corruption

当我运行程序时,在函数完成后出现异常“堆已损坏”

我读到如果您正在使用已释放的内存,或者当您正在写入超出数组索引的索引时,可能会导致此异常。但是这里没有任何情况适用。我已经阅读了一些问题的其他答案,但没有太大帮助。

`char fileNametoExport[26]="d:\\FOlder1\\part1.ipt";
 char WorkingFolderName[260] ="d:\\folder";
 int start = rFind(fileNametoExport, '\\');
 int finish = rFind(fileNametoExport, '.');
 if (start == -1)
 start = 0;
char partname[260];
strcpy(partname,substr(fileNametoExport, start, finish));
::AfxMessageBox((LPCTSTR)partname);
char xtfile[260];
char xmltxtfile[260];
strcpy(xtfile, strcat(WorkingFolderName, partname));
strcat(xtfile, "__Default.x_t");
strcpy(xmltxtfile, WorkingFolderName);
strcat(xmltxtfile,"_XT_SE_INV_Default_SOLID_0_Solid1_xt.xmt_txt");`

函数 rfind() 在 char 数组中查找 char 的出现-

int rFind(char* s, char c)
    {
    int sz = 0;
    char *tmp = s;
    while (*tmp != '\0')
    {
        sz++;
        tmp++;
    }
    for (int i = sz - 1; i >= 0; i--)
    {
        if (*(s + i) == c)
            return i;
    }
    return -1;
}

函数 substr() 获取从位置 x 到 y 的子字符串(y 不包括)

char* substr(char* s, const int b, const int f)
{
    char *str = new char[f - b];
    int t = 0;
    for (int i = b; i != f; i++)
    {
        str[t] = s[i];
        t++;
    }
    str[t] = '\0';
    return str;
}

P.S- 在提供输入时,我确保 fileNametoExport 始终包含“.”和 '\'。

最佳答案

  1. 您的程序不检查输入字符串的长度。您可以接收比缓冲区更长的字符串,程序将失败。
  2. 如果你的程序得到fileNametoExport = "d:\\somefolder\\somefilewithoutdot" , finish将为 -1 并且程序在 strcpy(partname,substr(fileNametoExport, start, finish)); 处失败.
  3. 程序在缓冲区后写入 char* substr(char* s, const int b, const int f)在行

    str[t] = '\0';
    

    因为t此时等于f-b ,大小为 str缓冲区。

函数_ASSERTE( _CrtCheckMemory( ) );来自 <crtdbg.h>在搜索这样的错误时非常有用。把它放在可疑代码周围,它会在你的错误之后失败。它仅在调试时有效。

关于c++ - 如何修复 C++ 中的 'Heap has been corrupted ' 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57157370/

相关文章:

java - 如果 Java 的分代垃圾收集器遍历 Activity 对象图,它们如何知道要对哪些对象调用 finalize()?

c++ - C++ 是否支持成员函数引用?

c++ - 在 Linux 终端上使用 C++ 编译示例 opengl 应用程序

c++ - 为什么我不能打印出我的字符串数组 C++?

c++ - 大 vector 上的 .push_back() 会导致 std::bad_alloc

c++ - 使用 malloc() 强制垃圾收集/压缩

c++ - 依赖范围和嵌套模板

c++ - Qt如何捕获指示所有gui元素准备就绪的事件

Java - 在不使用外部类或方法的情况下计算数组中的重复项?

javascript - Array.push() 和 console.log() 给出了不同的变量