0

What's wrong with this code (I minimized my whole code)? I can't figure out why pu.useIt(); causes a segmentation fault.

#include <memory>

using namespace std;

class Person {
    private:
    shared_ptr<string> name;

    public:
    void setName(shared_ptr<string> name) {
        this->name = name;
    }

    shared_ptr<string> getName() {
        return name;
    }
};

class PersonCreator {
    shared_ptr<Person> person;

    public:
    void createAmy() {
        shared_ptr<string> amysName = make_shared<string>("amy");
        person->setName(amysName);
    }
};

class PersonUser {
    public:
    void useIt() {
        PersonCreator pc;
        pc.createAmy();
    }
};

int main()
{
    PersonUser pu;
    pu.useIt();

    return 0;
}
0

1 Answer 1

2

You need to initialize person, now it is empty, default ctor of shared_ptr means that it points to nullptr:

void createAmy() {
        shared_ptr<string> amysName = make_shared<string>("amy");
        person = std::make_shared<Person>();  // added
        person->setName(amysName);
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Is default ctor of shared_ptr an extra information, you get? I only get return code 139
@Ben I don't understand, can you clarify your question? You got 139 exit code because there was not Person instance pointed by person, so setName was called for nullptr pointer. After this modification is your app still crashing?
Actually my minimization is wrong... Your answer is totally correct for my question.

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.