Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何修复';堆已损坏';c+中的错误+;?_C++_Arrays_Heap Memory_Heap Corruption - Fatal编程技术网

C++ 如何修复';堆已损坏';c+中的错误+;?

C++ 如何修复';堆已损坏';c+中的错误+;?,c++,arrays,heap-memory,heap-corruption,C++,Arrays,Heap Memory,Heap Corruption,当我运行程序时,在函数完成后,我得到异常“heap has corruption” 我已经读到,如果您正在使用已释放的内存,或者在写入超出数组索引的索引时,可能会导致此异常。但这些案例在这里都不适用。我读过一些问题的其他答案,但没有多大帮助 `char fileNametoExport[26]="d:\\FOlder1\\part1.ipt"; char WorkingFolderName[260] ="d:\\folder"; int start = rFind(fileNametoExp

当我运行程序时,在函数完成后,我得到异常“heap has 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()查找字符数组中出现的字符-

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独占)

注意-在输入时,我确保fileNametoExport始终包含“.”和“\”

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

    str[t] = '\0';
    
    因为此时
    t
    等于
    f-b
    str
    缓冲区的大小


  • 函数
    \u ASSERTE(\u CrtCheckMemory())
    的code>非常有用。把它放在可疑代码周围,它会在你的bug之后失败。它只在调试中起作用。

    那么,是什么让您认为上面的代码是错误的原因呢?顺便说一句,您的代码有错误,您应该使用char
    fileNametoExport[26]=“d:\\FOlder1\\part1.ipt”
    char WorkingFolderName[260]=“d:\\folder”。反斜杠必须以字符串文本形式转义。::AfxMessageBox((LPCTSTR)partname)~~这个消息框是否显示有效值?@ DokKalnter,不,它不显示有效值。@ SalaLIDBHAVSAR顺便说一下,保护自己免受堆损坏问题的最好方法是使用C++特性,如“代码> STD::String < /Calp>和<代码> STD::vector < /Cord>,而不是C字符串和数组。上面的代码是纯C代码。我提供的输入确保文件名始终包含“.”和文件扩展名
    
    str[t] = '\0';