简体   繁体   中英

Error when modifying vector member of another class

I have two classes and one has to change the value of a vector of the other class. This is the first one, where the vector X to be changed resides:

Grid.hpp

class Grid{
  public:
    vector<double> X;
}

The other class has a reference to the first class and has a function that should modify X:

BC.hpp

class BC{

  public:

  Grid &grid;
  BC(Grid grid);
  ~BC(){};
  void add_to_X(int n_values);
}

BC.cpp

BC::BC(Grid grid): grid(grid){}

void BC::add_to_X(int n_values){
  vector<double> new_X;
  for(int i=0; i<n_values; i++){
    new_X.push_back(0.1);
  }
  grid.X = new_X;

main.cpp

int main(){
// grid and bc classes initialized above
bc.add_to_X(10);
}

When I run the main.cpp above I get the error malloc: *** error for object 0x7fb6294027b0: pointer being freed was not allocated . I also tried another solution. I wrote a function into the class grid which assigns the new vector to the X vector from within the class grid itself, but still I have the same error. If I comment out the row grid.X = new_X; the error disappear. What is wrong with the code above? What is the right way of coding?

The problem is this line:

BC::BC(Grid grid): grid(grid){}

What this does is, it copies the argument that you pass to the constructor into a temporary grid . You then assign your member variable, a reference, to point to this temporary. However, as soon as the constructor exits, that temporary gets destroyed again, so your reference is left dangling.

So you either have to make it references all the way down:

BC::BC(Grid& grid): grid(grid){}

and then ensure that the caller keeps the respective Grid object alive, or have the BC store a copy of the Grid instead of just a reference.

As was suggested in the comments , you should use this opportunity to improve your debugging skills. Your dangling reference will be pointing to an invalid object when the crash happens. Dangling references are hard to detect automatically, so it's useful to know what such problems look like in the debugger. See if you can track down what's going wrong by analyzing the problem in the debugger before fixing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM