#include <iostream>
using namespace std;
class IntTest{
public:
IntTest(int intVal = 0) : val(intVal) { }
operator int(){
return val;
}
friend IntTest& operator+(const IntTest&,const IntTest&);
private:
int val;
};
IntTest& operator+(const IntTest &i1,const IntTest &i2){
static int nbuf = 0;
static IntTest buf[10]; //goes to 147 before a crash?
buf[nbuf] = i1.val + i2.val;
cout << nbuf << endl;
return buf[nbuf++];
}
int main(){
for(int x=0; x < 155; x++){
IntTest i = x;
IntTest i2 = x;
cout << "i + i2 = " << i + i2 << "\t" << x << endl;
}
}
Weird behavior
Anyone know why this program goes past 10 IntTest objects?
Accessing an array out of bounds doesn't necessarily create an instant crash. That's why arrays are unsafe - you can never know for sure if they're being overflowed or not. You may never see a crash at all, if the array overflow never writes over executable code or into invalid memory space.
In this particular case, you should just use std::vector and push_back each sum in the operator code.
In this particular case, you should just use std::vector and push_back each sum in the operator code.
Quote:Original post by Gink
Anyone know why this program goes past 10 IntTest objects?return buf[nbuf++];
My guess would be because everytime you call operator+, you increment nbuf, but never check to make sure it stays less than 10. Seeing as how you call operator+ 155 times, I imagine nbuf gets up to 155, well outside the range of your buf object.
CM
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement