Consider the below code:
#include <iostream>
using namespace std;
class Buffer {
public:
static const int BufferSize=5;
Buffer() {
for(this->index=0;this->index<=BufferSize;this->index+=1) {
BufArr[this->index]=0;
cout<<"index: "<<index<<"n";
}
}
int BufArr[BufferSize];
int index;
};
int main() {
Buffer b;
return 0;
}
If we run this code, it prints:
0
1
2
3
4
0
1
2
3
4
...
and keep printing, why? It should stop (as we have index<=BufferSize
condition).
Please help me understand this.
2
The condition of your loop is:
this->index<=BufferSize
Which means that in the last iteration index
will be 5
.
Then BufArr[this->index]
is accessing the array out-of-bounds which causes UB (undefined behavior). It means the standard gives no guarantee about the behavior of the program.
You need to use <
instead of <=
:
this->index<BufferSize
Live demo
A side note:
See: What’s the problem with “using namespace std;”?
Note:
As @AlanBirtles commented below although in principle when UB ensues anything can happen, in this simple case it is quite obvious why on most implementations the original code will produce an infinite loop:
index
is of the same type as the elements in BufArr
and is probably stored right after BufArr
in the object, and so when writing 0
to BuffArr[5]
it is essentially the same as assigning index
to 0
.
5
Arrays are 0 indexed. This means while you count 5 Values (1,2,3,4,5) Arrays count with: 0,1,2,3,4 your for-loop asks for smaller-equal to Buffersize (<=
) while it should be <
. Your array runs in the current state out of bounds which causes an overflow which again causes Undefined Behaviour