运行时检查失败 #2 - 变量周围的堆栈'x'已损坏

Run-Time Check Failure #2 - Stack around the variable 'x' was corrupted

本文关键字:堆栈 已损坏 周围 失败 检查 变量 运行时      更新时间:2023-10-16

我在以下代码中返回时收到此运行时检查失败。我相信类似的代码在程序的其他地方运行得很好。有什么想法吗?

String GetVariableName(CString symbol, CString filepath)
{
    char acLine[512];
    char acPreviousLine[512];
    CString csFile;
    FILE *fp;   
    csFile.Format("%svariables.txt", filepath);
    fp = fopen(csFile, "r");
    if (! fp)
        return("");
    for (;;)
    {
        strcpy(acPreviousLine, acLine);
        // NULL means we are out of lines in the file.
        if (myfgets(acLine, 511, fp) == NULL)
            break;
        // "END" indicates end of file
        if (! strcmp(acLine, "END"))
            break;
        if (! strcmp(acLine, csVarSymbol))
        {
            // Previous line should be variable name
            fclose(fp);
            // Following line results in Check Failure while in Debug mode
            return(acPreviousLine);
        }
    }   
    fclose(fp);
    return("");
}

上面的例子中没有变量'x',但我认为您编辑了错误消息!

acLine没有初始化,所以第一次将其复制到acPreviousLine时,您正在复制堆栈上发生的任何内容。在某些情况下,这可能会导致缓冲区溢出,从而导致堆栈损坏,而不是全部,因为您可能很幸运,在达到512字节之前在acLine中找到了一个null。

堆栈在返回时会被检查是否损坏,因为在所有堆栈变量周围插入了保护字(在这个平台和构建配置上——我认为它在Windows上,在VS上以调试模式编译)来检查是否存在该问题。

将acLine[0]初始化为0。