Sign in to follow this  
Gink

Weird behavior

Recommended Posts

Gink    100
Anyone know why this program goes past 10 IntTest objects?
#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; 
    }
}

Share this post


Link to post
Share on other sites
ApochPiQ    23064
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.

Share this post


Link to post
Share on other sites
Conner McCloud    1135
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this