Why is this code acting weird? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why is this code acting weird?

#include <iostream> using namespace std; int main() { int myArr[5]; for(int x=0; x<5; x++) { myArr[x+1] = 42; cout << x << ": " << myArr[x] << endl; } return 0; } i entered this code on pc and my anti-virus recognized it as a threat :/ and the output is strange too. why is that?

5th Mar 2017, 9:58 PM
Nara
Nara - avatar
4 Answers
+ 11
Yep. As others have pointed out, an array-out-of-bound issue. In normal cases, the program should crash. That sensitive antivirus though lol.
6th Mar 2017, 12:02 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
In myArr[x+1] = 42 your are trying to store the value in an invalid memory location. Your array have 5 positions [0, 1, 2, 3, 4], but when x = 4 the code try store the value in position number 5. Rewrite your code with myArr[x] = 42 and it will work.
5th Mar 2017, 10:06 PM
Kleber Leal
Kleber Leal - avatar
+ 3
trying to use memory not officially allocated to a variable leads to what is called a buffer over flow. the heap memory is overused unofficially. this is an attack used by some hackers and the stuxnet virus for overriding embedded systems( the one that overrode Iran's nuclear plant embedded systems resulting to a blast). be careful with such codes
5th Mar 2017, 10:24 PM
Michael Jaroya
Michael Jaroya - avatar
+ 1
@KleberLeal @JPM7 oh thanks now i get it :D actually this wasnt my code but i was curious.
5th Mar 2017, 10:08 PM
Nara
Nara - avatar