Runtime Check Error # 2 - Damage around the variable "x" was damaged

I get this runtime check when returning in the following code. I believe that similar code works 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("");
}
+3
source share
1 answer

There is no “x” variable in the above example, but I will assume that you edited the error message!

acLine is not initialized, so the first time you copy it to acPreviousLine, you copy everything that happens on the stack. This can lead to buffer overflows and therefore to damage the stack in some situations - not all, because you may be lucky and find zero in acLine before you get up to 512 bytes.

, ( , , , Windows, VS ), , .

acLine [0] 0.

+17

Source: https://habr.com/ru/post/1699208/


All Articles