1

Can somebody tell, why I have segmentation fault in that code? I have no idea why is that. I use Code:Blocks but online compilers have the same problems. I don't know where the problem is.

#include <iostream>
#include <queue>
#include <memory>

using namespace std;

class Task {   
private:
    queue <string> q;
    public:
    string input;
    void read (int hm)
    {
        for (int i=1;i<=hm;i++)
        { 
            cin>>input;
            q.push(input);
        }
    }
    void count()
    {
        cout<<q.back();
    }
};

int main()
{
    unique_ptr <Task> ptr;

    int how_many;
    cin>>how_many;
    ptr->read(how_many);
    ptr->count();
    return 0;
}

1 Answer 1

3

The pointer ptr is being used without being initialized. Use:

std::unique_ptr<Task> ptr = std::make_unique<Task>();

That being said you should also include the <string> header explicitly.

Sign up to request clarification or add additional context in comments.

1 Comment

And your count() will return the value of the most recent element rather than the number of elements. For that, use q.size(). Example: cplusplus.com/reference/queue/queue/size

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.