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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/268772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:11:03  来源:igfitidea点击:

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

c++stack

提问by James Winans

I receive this Run-Time Check Failure upon the return in the following code. I believe similar code is running fine elsewhere in the program. Any ideas?

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

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

回答by Airsource Ltd

There is no variable 'x' in the above example, but I'll presume you edited the error message!

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

acLine isn't initialised, so the first time you copy it to acPreviousLine, you are copying whatever happens to be on the stack. This can give you a buffer overflow and therefore stack corruption in some situations - not all, because you might be lucky and find a null in acLine before you get to 512 bytes.

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

The stack gets checked for corruption on return, because there are guard words (on this platform and build configuration - which I presume is on Windows, compiling on VS in debug mode) inserted around all stack variables to check for just that problem.

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

Initialise acLine[0] to 0.

将 acLine[0] 初始化为 0。