How to fix segmentation fault (run time error)?

  c++, dynamic-arrays, nullptr

I am wondering how to fix segmentation fault (run time error) when running my program? My program compiles with no errors and warnings. The issue might be caused by deleting dynamic variable names or something to do with initializing with nullptr. I am not exactly sure what is causing this issue. Here is the code:

  #include <iostream>
  
   using namespace std;
  
   class Kiosk
   {
      private:
          double adult_cost;
          double child_cost;
          double senior_cost;
          string * names;
          double total;
          int attendees;
          int index;
 
      public:
      Kiosk()
      {
          names = nullptr;
          index = 0;
          total = 0;
      }
 
      Kiosk(int ac, int cc, int sc)
     {
          adult_cost = ac;
          ac = 0;
          child_cost = cc;
          cc = 0;
          senior_cost = sc;
          sc = 0;
          index = 0;
 
      }
 
      double get_total()
      {
          attendees = adult_cost + child_cost + senior_cost;
          total = total + attendees;
          return total;   // Getter function to return the value of total
      }
 
      int set_counts(int adults, int children, int seniors)
      {
          string * names = new string[attendees]();
          // Initializing Dynamic Array to total count of attendees
          return adults, children, seniors;
      }
 
      void add_name(string& name)
      {
          names[attendees] = name;
          attendees++;
          return;
      }
         string get_names()
      {
          return * names;
      }
 
      ~Kiosk()
      {
         if (names != nullptr)
          {
              delete [] names;
          }
      }
 
  };
  // The goal of this program is to create an event ticket kiosk.
  // The user enters who is attending the events for the ticket price from the Kiosk.
  // The Kiosk will tell the user what the total cost is and tell the names to enjoy the show.
 
  int main()
  {
    //    prices for adults, children, seniors
      Kiosk * machine = new Kiosk(15, 10, 8);
 
      int act, cct, sct, count = 0;
      string name;
 
      cout << "How many adults? ";
      cin >> act;
      cout << "How many children? ";
      cin >> cct;
      cout << "How many seniors? ";
      cin >> sct;
 
      count = machine->set_counts(act, cct, sct);
 
      for (int i = 0; i < count; i++)
      {
         cout << "Name of attendee: ";
         cin >> name;
         machine->add_name(name);
     }

     cout << "Total cost: " << machine->get_total() << endl;
     cout << "Enjoy the show, " << machine->get_names() << "!n";

     // dispose of the machine dynamic variable
     delete machine;

     return 0;
 }

This is my program’s output:

How many adults? 1
How many children? 0
How many seniors? 1
Name of attendee: John
Segmentation fault

Source: Windows Questions C++

LEAVE A COMMENT