Brett L
Brett L

Reputation: 105

C++ pointer set to address, but inexplicably points to different values in different parts of program

I'm trying to use the pointer toRender to store the address of the closest triangle in my raycasting program. My first print statement indicates that it's working: printing out 1, which is the correct value for toRender->color.x for the closest triangle. However, once the program gets to the next print statement, it prints 0 for toRender->color.x. This is the color value for another triangle, but importantly, that triangle was not intersected for this pixel (this iteration of an outer loop), and the first cout didn't print 0 for this pixel. When I debugged the code, the address assigned to toRender remained the same, despite toRender->color.x giving different values at the two print statements. I don't know how to account for this.

I'm not sure if it's relevant, but world is a function argument: const std::vector<Triangle>& world, and Triangle is a struct.

        float minDist = 1000; // distance to closest sphere
        Triangle* toRender;

        // check for intersection with each triangle in the world
        for (Triangle triangle : world) {

            // distance to triangle
            double distTo;

            // distTo is set in intersectTriangle
            if(intersectTriangle(ray, triangle, distTo)){
                // set new minDist if closest
                if (distTo < minDist){
                    minDist = distTo;
                    toRender = &triangle;

                    cout << toRender->color.x << endl;

                }

            }
        }


        // don't render anything farther than 1000 away
        if(minDist < 1000) {
            cout << toRender->color.x << endl;
            // get color from closest shape
            double red = toRender->color.x * 255;
            double green = toRender->color.y * 255;
            double blue = toRender->color.z * 255;

            // set color
            color = make_colour(red, green, blue);

        }

Upvotes: 2

Views: 58

Answers (1)

Jesper Juhl
Jesper Juhl

Reputation: 31468

triangle is a variable containing a copy of an object in the container, that is scoped to the loop. It does not exist outside the loop, so the pointer you assign to toRender points to a destroyed object after the loop. That's Undefined Behaviour.

If you intended for triangle to refer to an object in the container rather than be a copy of one, then make it a reference (auto& triangle : ...

Upvotes: 2

Related Questions