mercredi 28 avril 2021

List push_back triggers a segmentation fault error [closed]

I have a class which has a private list. I've declared it in my .hh file like this:

   class Course{

   private:

      int id;
      list<string> sessions;

   public:


   Course(int c);

   ~Course();

   void read_course();

and then again in my constructor on the .cc file (i don't know if i have to do this again). I want to have it so that the constructor initialises it as an empty list:

#include "Course.hh"
#include <list>
#include <iostream>
using namespace std;

Course::Course(int c){
    id = c;
    list<string> sessions;

}

Course::~Course(){}

void Course::read_course(){
  int s;
  string nom;
  cin >> s;
  for(int i = 0; i < s; ++i){
      cin >> nom;
      sessions.push_back(nom);
  }
}

The read_course() method, when called, has to store s strings to the list, and i do this with a for loop and .push_back():

My problem is that when i execute it it gives me a segmentation fault (core dumped) error. I have tried initialising the list as

sessions = new list<string>;

and other stuff that I've found online, but the examples were mostly for vectors and I couldn't figure out why this happens or how to solve it. Any help will be appreciated!

Aucun commentaire:

Enregistrer un commentaire