+ 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?
4 odpowiedzi
+ 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.
+ 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.
+ 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
+ 1
@KleberLeal @JPM7 oh thanks now i get it :D actually this wasnt my code but i was curious.