-4

I have abstract class (Service) with two derived classes (Court and Machine). I also have a pointer array of Service, and I'm trying to read from a text file that includes information for both Court and Machine. To identify which information is for which class, I'm using an if.

My code compiles, but when executing I receive a segmentation fault. I'm aware this means I'm accessing memory that I shouldn't, but I'm not sure what I'm doing wrong.

I've never worked with pointer arrays. Am I'm doing something wrong when trying to input objects? I made sure to include both classes at the start of the program.

Service *listServices[20];
ifstream ArchService;
ArchService.open("Services.txt");

while(!ArchService.eof()) 
{
    for (int iA = 0; iA < 20; iA++) 
    {

        string clave, descripcion, deporte;
        int tiempomax, maxpersonas; 
        char tipo;
        double costo;
        bool instructor;
        ArchService >> clave >> tiempomax >> tipo >> costo;

        if (tipo == 'C' || tipo == 'E' || tipo == 'B') 
        {
            ArchService >> instructor;
            ArchService.ignore();
            getline(ArchService, descripcion);
            listServices[iA] = new Machine(clave, tiempomax, tipo, costo, instructor, descripcion);
        }

        else 
        {
            ArchService >> maxpersonas;
            ArchService.ignore();
            getline(ArchService, deporte);
            listServices[iA] = new Court(clave, tiempomax, tipo, costo, maxpersonas, deporte);
        }
        listServices[iA]->print();
    }
    ArchService.close();
}
Donald Duck
  • 6,488
  • 18
  • 59
  • 79
Lorraine
  • 23
  • 6

1 Answers1

0

Every element of listServices is allocated over and over again, with old values not being deleted, so they just remain dangling references and form multiple memory leaks. Probably this is the root cause. As been mentioned before, you'd rather remove that while(!ArchService.eof()) loop if all you want is filling the array of 20 list services.

bipll
  • 11,131
  • 1
  • 15
  • 31