jeudi 30 juin 2016

For loop alters values not specified in the loop declaration at every iteration

I have a tree structure in my program, in which each object contains a list of pointers to its children in a vector.

int main(int argc, char* argv[]){
    ...
    Compartment* head = readIn(argc, argv, count);

Where readIn(int,char*,int) reads in data from an outside file and creates the tree based on that:

Compartment* readIn(int argc, char* argv[], int &count){
    ...
    Compartment* head = nullptr;
    ... //reads in data
    if (parID == -1){
        Compartment* c = new Compartment(params...,nullptr); //head so no parent
        head = c;
    } else {
        Compartment* c = new Compartment(params...,Compartment::fndID(parID,head));
    }
    ...
    return head;
}

Where fndID(int,Compartment*) is a recursive DFS that returns a pointer to the Compartment with the specified ID, and the Compartment constructor uses push_back() to add the constructed object to its parents list of children.

I then construct a 2D matrix on the heap, and start a for loop that (non-destructively) deals with the tree. However, on the second iteration of the loop, I get a segfault! Upon investigating, I found that the vector of children of the head Compartment had become truncated, but that it had happened from the front! I was missing the first two values of the vector, leaving only the second two. However, when I checked the values immediately before the end of the first iteration of the for loop, the whole vector is there, so something must be happening at the end. My first thought is that I'm doing pointers wrong, but if so, how? Or is it something else entirely?

Aucun commentaire:

Enregistrer un commentaire