I have the following code :

``iterator = u.U.begin(); //u.U is a map<bitset,long>int sizeofIterator = u.U.size();for ( int pp = 0; pp<sizeofIterator; pp++ ){double *faux = new double[q];for (int k = 0 ; k<q ; k++){faux[k]=1;}for (int k=0; k<q ; k++){for (int i=0; i<I ; i++){faux[k]= faux[k]*successProbability(theta[k],a[i],b[i],c[i]);}faux[k] = faux[k]*nodeWeight[k];}double sum = 0;for (int k=0; k<q ; k++){sum += faux[k];}for (int k=0; k<q; k++){faux[k] = faux[k]/sum;faux[k] = iterator->second * faux[k];f[k] = faux[k]+f[k];for(int i = 0; i<I; i++){if(iterator->first[i]){double aux = faux[k];r[k*I+i]=r[k*I+i]+aux;}}}iterator++;}``

When that code is run, I've got a segmentation fault. I've got some conclusions and I know that the problem is in the line that's got

`` iterator++;``

## The iterator has to iterate 32 times (the size of the map) but the segfault occurs in the 18th iteration

TIP:

When I comment the aux in line:

r[k*I+i]=r[k*I+i]+aux;

i.e. I put the following

r[k*I+i]=r[k*I+i]+0;//+aux;

## All works (But I need to perform that sum, surely!)

¿Do you know why? ¿Can you help me please?

EDIT : We could not replicate the error on less code, it simply works, but is not the code we want to work :(

TIP: When I comment the aux in line: r[k*I+i]=r[k*I+i]+aux;

i.e. I put the following r[k*I+i]=r[k*I+i]+0;//+aux; All works (But I need to perform that sum, surely!)

This is called voodoo debugging, and is also associated with your inability to geenrate a smaller example. Basically you have, at some point, corrupted either your stack or heap (or both). Sometimes after corrupting these, you can continue, but have other function call be fragile. You error is not in the map or the iterator. There is little cause to believe the error is even in this function.

This leads to spurious and misleadding errors (serach for voodoo debugging on the web to find out more). I recommend a memory tool like valgrind, which might help.

Else, another apporach might be to put a full map traversal loop into a single line statement, and see at which point your structure becomes invalid, since above you are finding out its invalid when you go to use it, but its probably been invalid for a while.

note in the above code, you haven't given us I, which will break the code if too big, and you havent told us above nodeWeight, theta or F.

btw, if I had to bet on stack vs heap corruption, I would bet stack. Adding extra terms to an equation (as per your tip) creates and destroys temporaries, which is usually a stack thing. So if doing it makes a difference, they are often being create in the wrong place or similar.

SOLVED: Error was in the line

``````f[k] = faux[k]+f[k];
``````

Because the f vector was not initialized.

THANKS ALL!

Top