运行我的代码时出现分段错误(核心转储)问题

时间:2019-11-25 19:49:27

标签: c++ segmentation-fault coredump

我正在做的作业,无法弄清楚为什么当我尝试运行程序时出现错误“细分错误(核心已转储)。尝试了一段时间,我可以”没看到我哪里出错了。我研究了分段错误,并逐行遍历了我的代码,但我仍然不知道。对于使用C ++进行编码来说还是很新的。

//This program reads the last names of the candidates and the number of votes they receive. The\
 program sorts and outputs the candidates based on votes received in descending order.

#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

void openFile(ifstream&);
void getData(ifstream&, string [], int [], int &);
void computePercentages(int[], double [], int &);
void sortVotes(string [], int [], double [], int);
int findSmallestIndex(const int[], int, int);

const int SIZE = 30;

int main(){

   string name[SIZE];
   double percentages[SIZE];
   int votes[SIZE];
   int size, sum;
   ifstream in;

openFile(in);
   getData(in, name, votes, size);
   computePercentages(votes, percentages, sum);
   sortVotes(name, votes, percentages, size);
   for(int i = 0; i < size; i++)
      cout << name[i] << " " << votes[i] << " " << setprecision(4) << percentages[i] << endl;

   in.close();

   return (0);


}

void openFile(ifstream& in){
   string filename;
   cout << "Enter file name: ";
   cin >> filename;
   in.open(filename.c_str());
}

void getData(ifstream& in, string n[], int v[],int& s){
   int x = 0;
   for (int s = 0; s < SIZE; s++){
      n[s] = x;
      v[s] = x;
   }
   in >> n[s] >> v[s];
   while (!in.eof()){
      s++;
      in >> n[s] >> v[s];
   }
}

void computePercentages(int v[], double p[], int& sum){
   int total = 0;
   for (int i = 0; i < SIZE; i++)
      total = total + v[i];

   double factor = 100.0 / total;
   for(int i = 0; i < SIZE; i++)

      p[i] = factor * v[i];
}
void sortVotes(string n[], int v[], double p[],int s){
   for(int index = 0; s - 1; index++){
      int smallestIndex = findSmallestIndex(v, s, index)
      swap (n[index], n[smallestIndex]);
      swap (v[index], v[smallestIndex]);
      swap (p[index], p[smallestIndex]);
   }}

int findSmallestIndex(const int v[], int s, int start){
   int smallestIndex = start;
   for (int i = start +1; i < s; i++)
      if (v[i] < v[smallestIndex])
         smallestIndex = i;
   return smallestIndex;
}

void swap(string &a, string &b){
   string temp = a;
   a = b;
   b = temp;
}
void swap(int &a, int &b){
   int temp = a;
   a = b;
   b = temp;
}

void swap(double &a, double &b){
   double temp = a;
   a = b;
   b = temp;
}

就像我说的,我不知道我要去哪里错了。任何见解都会有所帮助。

1 个答案:

答案 0 :(得分:0)

在以下代码中,第一个循环将“ s”设置为SIZE,并且数组长度也均为“ SIZE”。

 void getData(ifstream& in, string n[], int v[],int& s){
       int x = 0;
       for (int s = 0; s < SIZE; s++){
          n[s] = x;
          v[s] = x;
       }
       in >> n[s] >> v[s];
       while (!in.eof()){
          s++;
          in >> n[s] >> v[s];
       }
    }

第二个循环(while)继续增加s(现在是s> SIZE),这会导致在执行in >> n[s] >> v[s];时导致无效的数组访问,因为n[s]v[s]现在访问超出分配给长度为SIZE的数组的内存。

此外,由于这是C ++,因此请使用std::arraystd::vector