1

When i am running this code I am getting below error as

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

int main()
{
    UINT8 temp[7];
    for (int i = 0; i <= 7; i++)
    {
        temp[i] = 0x01;
    }
    return 0;
}//The error falls here

Please help me.

4

7 回答 7

3

you are accessing array out of boundry

change:

for (int i = 0; i <= 7; i++)

to

for (int i = 0; i < 7; i++)

Or more C++ way:

std::fill_n(temp, 7, 0x01);  
于 2013-01-18T10:10:54.767 回答
2

the size of temp is 7 and the for loop reach 8 elements and not 7

change

for (int i = 0; i <= 7; i++)

by

for (int i = 0; i < 7; i++)

The array index in c start from 0. so if you go from index 0 to index 7 in your array that means you reach the 8th element in your array, but your array size is 7

于 2013-01-18T10:10:27.787 回答
2

The cycle should be excluding 7 - your array is of size 7, so there is no element with index 7 in it.

于 2013-01-18T10:10:37.030 回答
2

Declaring UINT8 temp[7]; creates an array of 7 variables. Starting from temp[0] to temp[6]

Your for loop however tries to access temp[7] which is undefined. The below loop will work

for (int i = 0; i < 7; i++)
{
    temp[i] = 0x01;
}
于 2013-01-18T10:11:35.930 回答
1

There are 7 elements in the array ([0..6]), your for loop tries to access 8 elements [0..7], therefore you get a corrupted stack.

于 2013-01-18T10:11:19.300 回答
1
for (int i = 0; i < 7; i++)
{
    temp[i] = 0x01;
}

This will help you.. you are writing back to the temp again.. that is the error you are getting

于 2013-01-18T10:15:52.637 回答
0

Note that in C and C++, array indexes are 0-based. So, if you have an array of N items, valid index values are 0,1,2,...,(N-1).

In your case, N = 7, so valid index values are 0,1,2,3,4,5,6.

So, substitute <= with < in your for loop:

UINT8 temp[7];
for (int i = 0; i < 7; i++)  // Use <, not <=
 ....

Moreover, there is a convenient _countof() macro available with VS in <stdlib.h>, which makes your code easier to read and maintain (instead of using the "magic number" 7 in your for loop):

for (int i = 0; i < _countof(temp); i++)

Using _countof(), if you change the size of the array, your loop code will still work, without modifying 7 to the new array size.

Note also that in C++11 it's possible to use range-based for loops (but they are not available in VC10/Visual Studio 2010, which you used as a tag in this question).

Note that if you want to fill a buffer with a given byte sequence you can use memset (a C-like way):

memset(temp, 0x01, sizeof(temp));

Or, more generally (even for elements larger than one byte), you can use C++ std::fill from <algorithm>:

fill(begin(temp), end(temp), 0x01);

Using an explicit algorithm like std::fill makes your code more readable, because it rises the "semantic level" of the source code (you just read "fill" instead of reading a "raw" for loop, the meaning of which you have to interpret).

于 2013-01-18T10:21:50.823 回答