Si Te Feng
Si Te Feng

Reputation: 190

A queue of pointers change its value

When I push a pointer of struct into a std::queue, and then poping the value, the value that I'm getting back would change to zero. I've simplified the actual code to illustrate the problem below. The head pointer in the real code is a class variable and contains other values. If I push head onto the queue, all other values that I get also become uninitialized.

What could be the issue here?

Note: PipePixel *head; is an instance variable declared in the class header file.

Add Head Function:

void LinkedGraph::addHeadPixel(int index) {

    PipePixel pixel = {NULL, 433, std::vector<PipePixel*>()};
    pixel.index = index;

    if (head==NULL) {
        pixelMap[index] = &pixel;
        head = &pixel;
    } else {
        printf("Already added head pixel! Px:%d\n", pixelMap[index]->index);
    }
}

Print Function: <-- Where problem occurs

std::queue<PipePixel*> printQueue;
printQueue.push(head);
printf("headIndex:%d\n", head->index); // headIndex:433

while (!printQueue.empty()) {

    PipePixel *child = printQueue.front();
    printf("childIndex:%d\n", child->index); //childIndex:0
    printQueue.pop();

    if (child == NULL) {
        printf("child is null"); // no output
        continue;
    }  
}

PipePixel Struct:

struct PipePixel {

    PipePixel *parent;
    int index; //pixel index
    std::vector<PipePixel*> children;
};

Upvotes: 0

Views: 1535

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

The problem here is that the variable pixel is local inside the LinkedGraph::addHeadPixel function. Once the function returns that object is destructed and the variable ceases to exist. If you have stored a pointer to a local variable, that pointer no longer points to a valid object, and dereferencing the pointer leads to undefined behavior.

My recommendation is to not use pointers at all, but let the compiler handle he object copying. For such small and simple objects its possible performance impact is negligible.

Upvotes: 1

Related Questions