[Solved] How to fix Segmentation Fault error when instantiating objects


We don’t have the full details on your string class, so this is hard to reproduce.

However, when you call sensors[0] = sensor1; you are copying your Sensor, but haven’t defined an assignment operator (or copy constructor for that matter).

You also do this in the Car constructor with

(*(m_sensors + i)) = Sensor(*(sensors + i));

Now without the full details of your string class, I can give suggestions that might help.

First, you are doing a lot of copying when you set up the senors.

You can collapse this

Sensor sensors[3];
Sensor sensor1 = Sensor(type), sensor2 = Sensor(), sensor3 = 
       Sensor();
sensors[0] = sensor1;
sensors[1] = sensor2;
sensors[2]= sensor3;

down to

    Sensor sensors[3]={{type}, {}, {}};

This might not solve the problem, but is less to look at.

Next, remove the setters. You can use delegating constructors to tie the two you have together, and avoid these.
This avoids some copies.

Look very carefully at what gets deep or shallow copied.

If you have two char * types,

char * word = "Hello";
char * another_word = word;

the second is a “shallow” copy. You need an equivalent of strcpy to actually make a different (“deep”) copy of the string.

3

solved How to fix Segmentation Fault error when instantiating objects