3

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

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("");
}
4

1 回答 1

17

上面的示例中没有变量“x”,但我假设您编辑了错误消息!

acLine 没有初始化,所以当你第一次将它复制到 acPreviousLine 时,你正在复制堆栈中发生的任何内容。这可能会给您带来缓冲区溢出,因此在某些情况下会导致堆栈损坏 - 并非全部,因为您可能很幸运并且在达到 512 字节之前在 acLine 中找到了一个空值。

返回时检查堆栈是否损坏,因为在所有堆栈变量周围插入了警戒词(在此平台和构建配置上-我假设在Windows上,在调试模式下在VS上编译)以检查该问题。

将 acLine[0] 初始化为 0。

于 2008-11-06T14:01:23.067 回答