ritual_code
ritual_code

Reputation: 147

C++ Memory Fault in template function <queue>

I'm getting a memory fault message at runtime, i'm new to STL so i'm not sure if I'm required to handle queue's in a special way like deleting them in functions or whatnot.

I traced the error to this function

template <typename T>  
bool contains(std::queue<T> set, T val){
        std::queue<T> hold;
        bool isContained = false;

        if (set.front() == val) isContained = true;
        while(!set.empty()){
                hold.push(set.front());
                set.pop();
                if (set.front() == val) isContained = true;
        }

        while(!hold.empty()){
                set.push(hold.front()); 
                hold.pop();
        }

        return isContained;
}

In my main() I successfully call this function 20 times for queue and then on the first time the function is called on a queue the program spits out a "Memory Fault" message between the two loops in the function.

I'm using gnu compiler.

Upvotes: 0

Views: 155

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476970

In your second call to set.front() there is no guarantee that the set isn't empty.

Upvotes: 2

Related Questions