Jump to content
  • Advertisement
Sign in to follow this  
Gink

Weird behavior

This topic is 4714 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!