Domanda

I have the following piece of code, which is part of a class, whose details hopefully are not important for answering that question. I don't want an exact solution to my problem, but only an explanation, how the behavior, I'm going to describe, can occur.

    Character operator+(Character c) {
        std::vector<float> resDensity(density);
        float l;
        float dh;
        for (int i = 0; i < domains.size(); i++) {
            for (int j = 0; j < c.domains.size(); j++) {
                l = (domains[i].intersection(c.domains[j])).length();
                //std::cout << l;
                dh = c.density[j] * l / domains[i].length();
                resDensity[i] += dh;
            }
        }
        std::vector<Domain> h(domains);
        return Character(h, resDensity);
    }

You probably noticed the commented cout statement. Due to a numeric bug in my program, I followed the falsy value until I detected the variable l. So I printed it to the console and found out, that the value is exactly the value I need, and also the program works just fine and the bug simply vanished. Uncommenting it, again, leads to the undesired misbehavior.

The Character class contains the fields domains and density, both vectors...

The length and intersection method:

    float length() {
        float res;
        for (int i = 0; i < is.size(); i++) {
            res += is[i].b - is[i].a;
        }
        return res;
    }

    Domain intersection(Domain d) {
        std::vector<Interval> hi;
        for (auto i = is.begin(); i != is.end(); i++) {
            for (auto j = d.is.begin(); j != d.is.end(); j++) {
                hi.push_back(i->intersection(*j));
            }
        }
        Domain hhh(hi);
        return hhh;
    }

I compiled the code with g++ --std=c++11 ...

g++ --version
g++ (GCC) 4.8.2 20131219 (prerelease)
È stato utile?

Soluzione

In your length() function the res variable is uninitialized:

    float res;
    for (int i = 0; i < is.size(); i++) {
        res += is[i].b - is[i].a;   // <-- uses an uninitialized res
    }

Altri suggerimenti

How is length() calculated on Domain? hhh is a local variable that you are returning, so a copy will be made. If length() depends on something that is not copied then you will see strange behaviour. What if you just change intersection() to return a float or create a different method called intersectionLength() which returns a float - do you still get the heisenbug?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top