简体   繁体   中英

Segmentation Fault occurring with Quicksort

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);
            }
        }

So right here in (part of) the main I get all the inputs and then call a function using some of the inputs. I am currently getting errors with the 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;
            }
        }
    }

Then in this function, I am sorting the code based on the field it is in and in incrementing/decrementing order.

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);
    }
}

This function serves to quick sort the games. I made it separately because quick sort is recursive and thus I can't quick sort inside the previous function. I got the quick sort from this website: http://www.cprogramto.com/c-program-quick-sort/ .

So basically, i'm trying to get all the inputs, stick them inside a function that sorts by field/order, and then specifically call the quick sort for the field.

The code compiles but I am currently receiving a segmentation fault 11 error whenever I attempt to run the code with something along the lines of qsort 2015 games decr, etc. When I omit the qsort, my code runs and works for the other sorting algorithms (not shown here) so I am sure the error is within quick sort. Will someone please help me see where exactly my error is?

Consider:

    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)

You set the array index (index1, index2) to the number of games .

That's not guaranteed to be less than the # of elements in the teams array.

So you wind up accessing the teams array out of bounds == segfault.

More Info: Compare your code to the site you got the algorithm from:

   ...
   index2 = lastIndex;

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

Index is the position in the array, where array[index] is the value . In your case, you are doing the comparison in the (inner) while loop correctly:

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

but you set the indexes incorrectly:

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

To make it more concrete, suppose there were 10 teams, but the first team (team #0) played 1000 games. Then your code does this:

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

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

The problem is teams[1000] isn't valid if there are only 10 teams and when you access an array out of bounds like this in C, you get a segfault (if you're lucky) or corrupt memory and/or a security bug (if you're unlucky).

Also, the suggestion made in comments to learn a source debugger (GDB, or whatever - depending on your platform) is critical to learning C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM