user8522538
user8522538

Reputation:

Run Time Check Failure Stack around the variable was corrupted

#include <stdio.h>
main()
{
int num[9], i = 0, count = 0;

while (i<10)
{
    scanf("%d", &num[i]);

    if (num[i] % 2 == 0)
    {
        count++;
    }
    i++;
}

printf("we have %d  double numbers\n", count);
}

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

What should I do?

Upvotes: 0

Views: 314

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

The valid range of indices that can be used to access an array with N elements is [0, N - 1] or that is the same [0, N ).

Thus the condition in the while statement

while (i<10)

has to be rewritten like

while (i < 9)

The reason of the error is using "magic numbers" throughout the program. Try to use named constants instead of magic numbers, In this case it will be easy to understand what magic number is used in what part of the code.

The program can look like

#include <stdio.h>

#define N 9

int main( void )
{
    int num[N];
    unsigned int count = 0;
    unsigned int i = 0;


    while ( i < N )
    {
        scanf( "%d", &num[i] );

        if ( num[i] % 2 == 0 ) ++count;

        i++;
    }

    printf( "we have %u  double numbers\n", count);
}

Instead of the while loop it would be better to use a for-loop because the variable i is not used outside the loop.

For example

#include <stdio.h>

#define N 9

int main( void )
{
    int num[N];
    unsigned int count = 0;

    for ( unsigned int i = 0; i < N; i++ )
    {
        scanf( "%d", &num[i] );

        if ( num[i] % 2 == 0 ) ++count;
    }

    printf( "we have %u  double numbers\n", count);
}

A more correct approach of declaring indices of arrays is using the type size_t for them.

In fact the array is not used in the program. You could count even entered values without using an array.

Take into account that according to the C Standard the function main without parameters shall be declared like

int main( void )

Upvotes: 2

frslm
frslm

Reputation: 2978

Your while loop hits all values of i from 0 to 9 inclusive, but attempting to access num[9] takes you out of bounds. You'll need to reduce the while loop range:

while (i<9) {
    ...
}

In addition, you really should give your main() function a return type, since modern compilers don't tolerate it being missing:

int main()
{
    ...

    return 0;
}

Upvotes: 4

Related Questions