1

I'm having a quite strange problem with the fwd_iterator that I'm implementing:

if I use the iterators in methods defined inside the class, they work, but if I create a method with global scope in which I use iterators, valgrind says that I'm attempting to access to uninitialised memory.

It seems like iterators created outside the class cannot read a private attribute of the class (even with public methods created to do this).

This is the global-scope method:

template<typename T, class Pred>
int evaluate(SparseMatrix<T> &sm, Pred pred){
    typename SparseMatrix<T>:: iterator begin, end;
    int count=0;
    begin=sm.begin();
    end=sm.end();
    while(begin!=end){
            if(pred(*(begin->data))) count++;
            begin++;
    }
    int dcount=0;
    if(pred(sm.getDef())) dcount = ((sm.getRows() * sm.getCols()) - sm.getSize());
    return count+dcount;
}

This is the inside-class method:

void print_it() {
    iterator x=begin();
    iterator y=end();
    int i=1;
    while(x!=y){ 
        cout<<i<<".("<<(x->i)<<","<<(x->j)<<")="<<*(x->data)<<endl;
        ++x;
        i++;
    }
    if(x==y) cout<<"End."<<endl;
    cout<<endl;
}

Solved: iterator class has two attributes, value_type val, and sm, a pointer to the class itself. In operator=(const iterator& other) I forgot to add after val=other.val; the sm=other.sm; line.

Now everything works!

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Vektor88
  • 4,841
  • 11
  • 59
  • 111
  • What line of source code does valgrind implicate? – Robᵩ Feb 09 '12 at 16:39
  • 2
    FWIW, `begin` is assigned to, while `x` is initialized. Perhaps your `SparseMatrix::operator=(SparseMatrix::iterator)` is broken? – Robᵩ Feb 09 '12 at 16:41
  • There is a lot of code that you aren't showing us. Unless someone guesses correctly, please follow the instructions at http://sscce.org : create a minimal, complete, compilable copy of your program and paste that here. – Robᵩ Feb 09 '12 at 16:45
  • Yes!!! It was operator= of the iterator! I forgot to assign a value to a private attribute, this causes lots of problems if the iterators are created outside the class. Now it's been fixed! – Vektor88 Feb 09 '12 at 16:46
  • 1
    Vektor88, it is fine to post a complete answer to your own question – Johan Lundberg Feb 09 '12 at 16:49
  • I'm already editing my post ;) – Vektor88 Feb 09 '12 at 16:51
  • @Vektor88: Rather tuen editing yout question, please post an actual answer; it's less confusing thay way. – Keith Thompson Feb 09 '12 at 17:31
  • @KeithThompson I can't do it. I've to wait 8 hours since I ask the question to answer myself, because my reputation is under 100. – Vektor88 Feb 09 '12 at 17:38

1 Answers1

1

iterator class has two attributes, value_type val, and sm, a pointer to the class itself. In operator=(const iterator& other) I forgot to add after val=other.val; the sm=other.sm; line.

Now everything works!

Vektor88
  • 4,841
  • 11
  • 59
  • 111