-1

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! 

    }
}
Filburt
  • 17,626
  • 12
  • 64
  • 115
cdjk
  • 3
  • 3

3 Answers3

1

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();
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

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();
alediaferia
  • 2,537
  • 19
  • 22
  • Sorry, but could you explain to me how does pair1->read_names() dereference the pointer, I thought '->' is just an operation to get access to the members of the type.. ? – cdjk Jun 23 '15 at 19:40
  • both `->` and `*` dereference a pointer and both allow you to access member instances. Here you find a more detailed answer http://stackoverflow.com/questions/1238613/what-is-the-difference-between-the-dot-operator-and-in-c – alediaferia Jun 23 '15 at 20:40
0

It's necessary to generate object about Name_pairs.

Name_pairs* pair1;

-> Name_pairs* pair1 = new Name_pairs();