Stevesanenar
Stevesanenar

Reputation: 1

Segmentation Fault (Core Dumped) After reading from file

I am trying to read a .txt file which looks something like this...

Rhombus 118.5 112.4 69.9

I am then trying to initialise my constructor for the Shapes class with the parameters or values 118.5, 112.4, 69.9. However, I am getting a Segmentation Fault (Core Dumped) error - and I know which line it is coming from in my code. I just don't know how to resolve it...

My code is below...

istream& inputpoints(istream &is, Shapes * & shape)
{
   string name;
   double x, y, z;
   if (is >> name) {
       if (is >> x >> y >> z) {
           *shape = Shapes(x, y, z); // Segementation fault (core dump) happening here
       }
   }
   return is;
}

I believe it is the line *shape = Shapes(x, y, z) that is causing all this problem. If I don't put the * before shape, then I get a Shapes can't be assigned to Shapes* error.

Would appreciate it if someone could help me out here.

Thanks

Upvotes: 0

Views: 283

Answers (1)

selbie
selbie

Reputation: 104579

Several issues. Primarily, you are assigning a pointer to temporary (stack) object to an out param.

For better style and readability, declare your function such that the second parameter is a pointer to a pointer to a ppShapes.

istream& inputpoints(istream &is, Shapes** ppShapes)
{

To fix the main problem, change this line:

*shape = Shapes(x, y, z); // Segementation fault (core dump) happening here

To be this:

*ppShapes = new Shapes(x, y, z);

Invoke inputpoints as follows:

Shapes* pShapes = NULL;

istream = inputpoints(istream, &pShapes);

Upvotes: 1

Related Questions