1

In the following code in my program (simplified of course), the output in funcA and funcB are different, meaning the pointer's value got changed somewhere along the way. I wasn't able to comfirm that the address of face changed as this error magically doesn't pop up in the debugger (QT Creator's debugger). But here's the code:

void funcA() {
    Face *face = funcB();

    if (face != NULL) {
        cout << "in funcA " << face->vertices[0] << endl;
    }
}

Face * funcB() {
    vector<Face> faces;
    //populate faces
    ...

    Face *face = &(faces[index]);
    cout << "in funcB " << face->vertices[0] << endl;
    return face;
}

Though the output changes depending on where my mouse clicks, the output in the two functions above vary wildly (in funcB it would be for example 30, and in funcA it would become 18117600 ... I only have 60 faces!) Also it seems to show up randomly, not all the time.

Any assistance will be greatly appreciated.

confusedKid
  • 3,231
  • 6
  • 30
  • 49

3 Answers3

5

First of all using raw pointers with STL containers can be dangerous.

vector<Face> faces; is local to funcB(), so after the function returns it is destroyed and are left with a dangling pointer (which was once pointing to a valid local value). Using a dangling pointer invokes Undefined Behaviour.

Community
  • 1
  • 1
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
4

You're returning a pointer to a local value that no longer exists after you return.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
3

You are returning the address of a local variable faces[index] which is not valid once funcB returns. The objects in the vector faces is deleted as soon as the funcB terminates, and you are returning the address of a object which has been deleted. This will invoke undefined behavior.

Naveen
  • 74,600
  • 47
  • 176
  • 233
  • Do you have any suggestions on the best way to fix it? – confusedKid Dec 08 '10 at 04:42
  • 2
    "The best way to fix it" depends on basically everything else that you're doing in these functions. What are you trying to accomplish? Why is 'faces' local in your function? Why did you think returning a pointer was the right thing to do? – Karl Knechtel Dec 08 '10 at 04:45
  • faces is supposed to be a temp vector to keep track of all the faces in the terrain that were intersected by a ray, so I can later find out which face is the closest to my camera. I wanted to return the pointer to the face in the faceList in my terrain so I can change the color of the face in another function. – confusedKid Dec 08 '10 at 04:48