Temporary objects are temporary.

Find the cause of a segmentation fault in:

    vector<grade>::iterator front = student_grades(sr1).begin();
    vector<grade>::iterator end = student_grades(sr1).end();
    while ( front != end ) {
        if ( is_numeric_grade( *front ) )
            ...
        front++;
    }

The vector returned by student_grades(sr1) is a temporary object, whose lifetime ends when the enclosing full expression has been evaluated. Thus front is an iterator that points into a vector that no longer exists. Similarly end is an iterator that points into a different vector that no longer exists. In effect, both front and end are dangling pointers.

The solution is to extend the lifetime of the vector that is returned by student_grades. One way to do that is to store it into a local variable:

    {
        vector<grade> temp = student_grades(sr1);
        vector<grade>::iterator front = temp.begin();
        vector<grade>::iterator end = temp.end();
        while ( front != end ) {
            if ( is_numeric_grade( *front ) )
                ...
            front++;
        }
    }


Last updated 3 December 1997.