So this is a problem I noticed with a small project I'm working on and I can't figure out what's going on, or what to search to fix it, so I wrote this small program to recreate the problem. I haven't worked with c++ in a few years so apologies if this is a really obvious problem.
#include <iostream>
#include <vector>
using namespace std;
class Cell{
int score;
Cell* next_l;
Cell* next_r;
public:
Cell(int s = 0, Cell *r = nullptr, Cell *l = nullptr){
this -> score = s;
this -> next_l = l;
this -> next_r = r;
}
int getScore(){
return this -> score;
}
void disp(){
cout << "Score: " << this -> score << endl; //Problem Line
if(this -> next_r != nullptr){
this -> next_r -> disp();
}
if(this -> next_l != nullptr){
this -> next_l -> disp();
}
}
};
// returns a cell that's the head of a binary tree
// formed by replacing last two cells in the vector
// with a Cell pointing to those two cells instead,
// and then calling this function on that new vector of cells.
Cell make_tree(vector<Cell> &cells){
if(cells.size() == 1){
return cells[0];
}else{
Cell c1 = *(cells.end() - 1);
cells.pop_back();
Cell c2 = *(cells.end() - 1);
cells.pop_back();
Cell cell = Cell(c1.getScore() + c2.getScore(), &c1, &c2);
cells.push_back(cell);
return make_tree(cells);
}
}
int main(){
vector<Cell> cells;
for(int i = 0; i < 3; i++){
Cell *ptr{new Cell(i)};
cells.push_back(*ptr);
}
Cell head = make_tree(cells);
head.disp();
return 0;
}
So the line that I marked as //Problem Line
is where I faced confusion while debugging. After printing the score, for some reason, all the values in the tree after a certain depth get replaced by random junk. This eventually leads to a segmentation fault. I have no idea how to proceed with fixing this problem.