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;
}
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?
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 ] );
}
you trigger a buffer-overflow. your array 'numbers' is 10 items big, you access the 11th item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With