Why class object as pointer gives segmentation error, when the usual class object does not

85 Views Asked by At

I don't understand as to why the code below gives a segmentation fault upon use of a pointer object. The code works fine, if non-pointer object is used, but gives a segmentation fault if pointer object is used to update the private vector member 'name'. The only way I got the pointer to work is to create a getter function for the vector member 'name', and use it as argument for the read_names() function.

Could the CPP experts explain why this is happening..?

This is the cpp file.

#include "iostream"
#include "string"
#include "vector"

using namespace std;
#include "name_pairs.h"


int main()
{
    // The 2 lines below here is what works.
    // Name_pairs pair1;
    // pair1.read_names();

    //This part below gives segmentation fault.
    Name_pairs* pair1; 
    pair1->read_names();
    delete pair1;
    return 0;
}

This is the header file.

class Name_pairs
{
public:
    void read_names();
    // prompts the user for an age for each name. 

    void print();

private:

    vector<string> name;
    vector<double> age;

};

void Name_pairs::read_names()
{
    // string in;
    for (string in; cin>>in;)
    {
        name.push_back(in); //segmentation fault occurs here! 

    }
}
3

There are 3 best solutions below

2
On BEST ANSWER

The following code

Name_pairs* pair1;

Only declares a pointer. The code immediately after:

pair1->read_names();

Dereferences the pointer. But since the pointer has not been initialized to point to any allocated memory your program crashes.

Ensure your pointer is initialized to an allocated instance actually:

Name_pairs* pair1 = new Name_pairs();
0
On

You declare a pointer then never initialize it

Name_pairs* pair1; 
pair1->read_names();

In fact, this doesn't even need to be a pointer

Name_pairs pair1{};
pair1.read_names();
0
On

It's necessary to generate object about Name_pairs.

Name_pairs* pair1;

-> Name_pairs* pair1 = new Name_pairs();