Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

I'm studying for an exam and this is on my practice test. The question is "Which type of error does the following code fragment cause?"

I was pretty sure there would be no errors, but I also can't get it to compile in VS13, I get the error:

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

    const int MAX = 500;
    int main(void)
    {
        int foo[MAX];
        for (int i = 0; i <= MAX; i++)
        {
            foo[i] = i * 2;
            cout << foo[i] << endl;
        }

    cout << "Press any key to exit." << endl;
    cin.ignore(2);

    return 0;
    }
like image 513
arsis-dev Avatar asked Aug 26 '14 23:08

arsis-dev


2 Answers

Valid indexes for foo are from 0 to MAX-1 inclusive. MAX is past the end of the array.

Your loop runs up to, and including, MAX. This writes beyond the end of the array, corrupting the stack.

Either increase the array size to MAX+1 so that MAX is in range; or change the loop condition to i < MAX to stop before reaching MAX.

like image 73
Mike Seymour Avatar answered Sep 25 '22 11:09

Mike Seymour


This problem is caused when you try to write too much data to a particular memory address. Typical causes are writing more to a string buffer than you have room for.

ie

void myfun()

{

    char mybuf[10];



    strcpy(mybuf, "This is definitely more than 10 characters long, it will also cause a Run-Time Check");

}

Another cause of this is when you are using memset/ZeroMemory to initialise a structure or array with the wrong size.

struct MyStruct

{

    int var;

};



void myfun2()

{

    MyStruct ms;



    ZeroMemory(&ms, 20); //since MyStruct is only one variable in the struct this will cause problems

}

A third possible problem is if you are accidentaly moving a pointer.

void myfun3()

{

    int a;

    int*b = &a;



    a++;

    *a = 20;

}

Of course, these problems are not so easy as above to find out, but I hope this will get you on the right track. But this happens and will break at the end of the function that the stack is corrupted in while it is returning. So the best place to look would be in the function that your LoggerThread variable is in.

like image 44
RISHABH DUBEY Avatar answered Sep 25 '22 11:09

RISHABH DUBEY