Question

I was coding some homework (101 level). When I tried to compile the code, I got some virus alert from bit defender:

#include <stdio.h>

int main ( void ) {
int numbers [10];
int i, temp;

for (i = 1; i <= 10; ++i)
    numbers[i] = 0;

printf("Enter up to 10 integers. input '-1' to finish \n");

for (i = 0; i < 10; i++) {
    scanf("%d", &temp);
    if (temp == -1) {
        break;
    } else {
        numbers [i] = temp - 1;
    }
}

for (i = 1; i <= 10; ++i)
    printf("the numbers are: %d\n", numbers[i]);

return 0;
}

virus alert print screen

I believe the problem is with this piece of code:

    for (i = 1; i <= 10; ++i)
        numbers[i] = 0;

Why the trojan virus alert? what did I do?

Was it helpful?

Solution

Don't pay attention some antivirus programs recognize the compiled items as virus, it does the same avast with visual studio, just add exception to your antivirus list. But your code has some problems indeed.

  • for (i = 1; i <= 10; ++i) is incorrect, because the arrays in C start on 0, and second to initialize variables you don't need to do for loops you can assign them values like any other variable.
  • numbers [i] = temp - 1 The way you store the values in the array is not so good, because you are altering the inputed values when you do -1.

a

/*For the array initialization.*/
int numbers[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

/*For inputing the values.*/

for ( i = 0; i < 10; i++ ){
    scanf( "%d", &temp );
    if( temp == -1 ){
        numbers[ i ] = -1;
        break;
    else{
        numbers[ i ] = temp;
    }
}

/*For the printing. */

for( i = 0; i < 10 ; i++ ){
    if( numbers[ i ] == -1 ){
        break;
    }
    printf( "numbers[%d] is %d", i, numbers[ i ] );
}

OTHER TIPS

you trigger a buffer-overflow. your array 'numbers' is 10 items big, you access the 11th item.

Use i=0 instead of i =1 because in C array indexes start at 0

size of array is 10 so the last index is 9 So you are accessing the array index which is out of bound in numbers[10], so it's undefined behaviour

Array would be like this :

numbers[0] ,numbers[1], . . . numbers[9]

modify code to this :

for(i=0;i<10;i++)
  printf("%d\t",numbers[i]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top