【问题标题】:Segmentation Fault occurring with Quicksort使用快速排序发生分段错误
【发布时间】:2016-06-04 17:00:17
【问题描述】:
int main() {
    int yearsToLoop;
    cin >> yearsToLoop;
    annual_stats* ptr = new annual_stats [yearsToLoop];
    for (int i = 0; i < yearsToLoop; i++)
    {
        int annualYear;
        cin >> annualYear;
        ptr[i].year = annualYear;
        for (int j = 0; j < NO_TEAMS; j++)
        {
            string team_name;
            getline(cin, team_name, '\t');
            strcpy(ptr[i].teams[j].team_name, team_name.c_str());

            int games;
            cin >> games;
            ptr[i].teams[j].games = games;

            float pts_per_game;
            cin >> pts_per_game;
            ptr[i].teams[j].pts_per_game = pts_per_game;

            int total_points;
            cin >> total_points;
            ptr[i].teams[j].total_points = total_points;

            int scrimmage_plays;
            cin >> scrimmage_plays;
            ptr[i].teams[j].scrimmage_plays = scrimmage_plays;

            float yds_per_game;
            cin >> yds_per_game;
            ptr[i].teams[j].yds_per_game = yds_per_game;

            float yds_per_play;
            cin >> yds_per_play;
            ptr[i].teams[j].yds_per_play = yds_per_play;

            float first_per_game;
            cin >> first_per_game;
            ptr[i].teams[j].first_per_game = first_per_game;

            int third_md;
            cin >> third_md;
            ptr[i].teams[j].third_md = third_md;

            int third_att;
            cin >> third_att;
            ptr[i].teams[j].third_att = third_att;

            int third_pct;
            cin >> third_pct;
            ptr[i].teams[j].third_pct = third_pct;

            int fourth_md;
            cin >> fourth_md;
            ptr[i].teams[j].fourth_md = fourth_md;

            int fourth_att;
            cin >> fourth_att;
            ptr[i].teams[j].fourth_att = fourth_att;

            int fourth_pct;
            cin >> fourth_pct;
            ptr[i].teams[j].fourth_pct = fourth_pct;

            int penalties;
            cin >> penalties;
            ptr[i].teams[j].penalties = penalties;

            int pen_yds;
            cin >> pen_yds;
            ptr[i].teams[j].pen_yds = pen_yds;

            string top_per_game;
            cin >> top_per_game;
            strcpy(ptr[i].teams[j].top_per_game, top_per_game.c_str());

            int fum;
            cin >> fum;
            ptr[i].teams[j].fum = fum;

            int lost;
            cin >> lost;
            ptr[i].teams[j].lost = lost;

            int to;
            cin >> to;
            ptr[i].teams[j].to = to;
        }
    }
    int numberOfC;
    cin >> numberOfC;

    for (int i = 0; i < numberOfC; i++)
    {
        string command;
        cin >> command;

        if(command == "qsort") {
            string command2;
            cin >> command2;
            int num = atoi(command2.c_str());
            if (num >= 2010)
            {
                string year;
                year = command2;
                string field;
                cin >> field;
                string order;
                cin >> order;
                qSortYearFieldOrder(year, field, order, ptr, yearsToLoop);
            }
        }

因此,在(部分)main 中,我获取所有输入,然后使用一些输入调用函数。我目前遇到 qSortYearFieldOrder(year, field, order, ptr, yearsToLoop) 错误。

void qSortYearFieldOrder(string year, string field, string order, annual_stats* ptr, int amountYears) {
    int yearIndex = 0;
    if  (amountYears == 1) {
        yearIndex == 0;
    }
    else {
        if (year == "2010") {
            yearIndex = 0;
        }
        else if (year == "2011") {
            yearIndex = 1;
        }
        else if (year == "2012") {
            yearIndex = 2;
        }
        else if (year == "2013") {
            yearIndex = 3;
        }
        else if (year == "2014") {
            yearIndex = 4;
        }
        else if (year == "2015") {
            yearIndex = 5;
        }
    }

    if (field == "team_name") {
        if (order == "decr") {


            cout << "\n\nDecreasing Order" << endl;
            for (int i = 0; i < NO_TEAMS; i++) {
                cout << ptr[yearIndex].teams[i].team_name;
            }
        }
        else if (order == "incr") {

            cout << "\n\nIncreasing Order" << endl;
            for (int i = 0; i < NO_TEAMS; i++) {
                cout << ptr[yearIndex].teams[NO_TEAMS - 1 - i].team_name;
            }
        }
    }
    else if (field == "games") {
        if (order == "decr") {
             quicksortGames(ptr, 0, NO_TEAMS - 1, yearIndex, order);
            cout << "TEAM" << "\t\t" << "Number Of Games Decreasing";
            for (int i = 0; i < NO_TEAMS; i++) {
                cout << ptr[yearIndex].teams[i].team_name << " " << ptr[yearIndex].teams[NO_TEAMS - 1 - i].games;
            }
        }
        else if (order == "incr") {
            quicksortGames(ptr, 0, NO_TEAMS - 1, yearIndex, order);  
            cout << "TEAM" << "\t\t" << "Number Of Games Increasing";
            for (int i = 0; i < NO_TEAMS; i++) {
                cout << ptr[yearIndex].teams[NO_TEAMS - 1 - i].team_name << " " << ptr[yearIndex].teams[i].games;
            }
        }
    }

然后在这个函数中,我根据代码所在的字段和递增/递减顺序对代码进行排序。

void quicksortGames(annual_stats* pointer, int firstIndex, int lastIndex, int yearIndex, string order)
{
    //declaring index variables
    int pivotIndex, temp, index1, index2;

    if(firstIndex < lastIndex)
    {
        //assigning first element index as pivot element
        pivotIndex = pointer[yearIndex].teams[firstIndex].games;
        index1 = pointer[yearIndex].teams[firstIndex].games;
        index2 = pointer[yearIndex].teams[lastIndex].games;

        //Sorting in Ascending order with quick sort
        while(index1 < index2)
        {
            while(pointer[yearIndex].teams[index1].games <= pointer[yearIndex].teams[pivotIndex].games && index1 < lastIndex)
            {
                index1++;
            }
            while(pointer[yearIndex].teams[index2].games <= pointer[yearIndex].teams[pivotIndex].games)
            {
                index2--;
            }

            if(index1<index2)
            {
                //Swapping opertation
                temp = pointer[yearIndex].teams[index1].games;
                pointer[yearIndex].teams[index1].games = pointer[yearIndex].teams[index2].games;
                pointer[yearIndex].teams[index2].games = temp;
            }
        }

        //At the end of first iteration, swap pivot element with index2 element
        temp =  pointer[yearIndex].teams[pivotIndex].games;
        pointer[yearIndex].teams[pivotIndex].games =  pointer[yearIndex].teams[index2].games;
        pointer[yearIndex].teams[index2].games = temp;

        //Recursive call for quick sort, with partiontioning
        quicksortGames(pointer, firstIndex, index2-1, yearIndex, order);
        quicksortGames(pointer, index2+1, lastIndex, yearIndex, order);
    }
}

此功能用于快速排序游戏。我单独制作它是因为快速排序是递归的,因此我无法在前一个函数中快速排序。我从这个网站得到了快速排序:http://www.cprogramto.com/c-program-quick-sort/

所以基本上,我正在尝试获取所有输入,将它们粘贴在按字段/顺序排序的函数中,然后专门调用该字段的快速排序。

代码可以编译,但是当我尝试使用类似于 qsort 2015 games decr 等的内容运行代码时,我目前收到分段错误 11 错误。当我省略 qsort 时,我的代码运行并适用于另一个排序算法(此处未显示),因此我确定错误在快速排序范围内。有人可以帮我看看我的错误到底在哪里吗?

【问题讨论】:

  • 如果你在调试器中运行它(比如gdb),它会准确地告诉你是哪一行代码导致了段错误。您甚至可以在导致它的状态下查看变量的值。

标签: c++ c sorting segmentation-fault


【解决方案1】:

考虑:

    pivotIndex = pointer[yearIndex].teams[firstIndex].games;
    index1 = pointer[yearIndex].teams[firstIndex].games;
    index2 = pointer[yearIndex].teams[lastIndex].games;
    ...
    while(pointer[yearIndex].teams[index1].games <= pointer[yearIndex].teams[pivotIndex].games && index1 < lastIndex)

您将数组索引 (index1, index2) 设置为游戏数

这不能保证小于团队数组中的元素数。

因此,您最终会越界访问团队数组 == segfault。

更多信息:将您的代码与您获得算法的网站进行比较:

   ...
   index2 = lastIndex;

    //Sorting in Ascending order with quick sort
    while(index1 < index2)
    {
        while(array[index1] <= array[pivotIndex] && index1 < lastIndex)
        {
            index1++;
    ....

Index 是数组中的位置,其中array[index] 是。在您的情况下,您正在(内部)while 循环中正确进行比较:

    while(pointer[yearIndex].teams[index1].games <= pointer[yearIndex].teams[pivotIndex].games && index1 < lastIndex)

但是你错误地设置了索引:

    index1 = pointer[yearIndex].teams[firstIndex].games;

为了更具体,假设有 10 支球队,但第一支球队(0 号球队)打了 1000 场比赛。然后你的代码会这样做:

    index1 = pointer[yearIndex].teams[0].games; // index1=1000

    while(pointer[yearIndex].teams[1000].games <= 
              pointer[yearIndex].teams[1000].games && 1000 < 9)

问题是如果只有 10 个团队并且当您在 C 中访问这样的数组越界时,团队 [1000] 无效,您会遇到段错误(如果幸运的话)或损坏的内存和/或安全漏洞(如果你不走运的话)。

此外,在 cmets 中提出的学习源代码调试器(GDB 或其他 - 取决于您的平台)的建议对于学习 C 至关重要。

【讨论】:

  • 感谢您的回答!抱歉,我需要澄清一下,因为我无法理解(我的错)你的评论。我将数组索引设置为显示游戏的部分,因为我试图在游戏分数之间进行排序。除此之外,比赛的数量等于球队的数量,因为每支球队打一场比赛。说了这 2 句话,我是否仍然可以通过绑定访问团队数组?
  • @somanyerrorswhy 扩展答案,希望能更清楚。另外:队伍的数量不能等于比赛的数量,因为一场比赛至少需要 2 支队伍,对吧?
猜你喜欢
  • 2017-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
相关资源
最近更新 更多