arsis-dev
arsis-dev

Reputation: 453

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

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;
    }

Upvotes: 17

Views: 132457

Answers (3)

Aaron
Aaron

Reputation: 11

It's usually allocating an array member past the max. I made a little password cracker with a large source array and no probs. I found I was calling an extra cycle past the max array size due to a loop condition mistake.

Upvotes: 0

RISHABH DUBEY
RISHABH DUBEY

Reputation: 91

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.

Upvotes: 5

Mike Seymour
Mike Seymour

Reputation: 254421

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.

Upvotes: 23

Related Questions