confusedKid
confusedKid

Reputation: 3251

C++ returned pointer points to something other than what was returned from the function

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.

Upvotes: 1

Views: 283

Answers (3)

Prasoon Saurav
Prasoon Saurav

Reputation: 92854

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.

Upvotes: 5

Fred Larson
Fred Larson

Reputation: 62053

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

Upvotes: 4

Naveen
Naveen

Reputation: 73433

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.

Upvotes: 3

Related Questions