0

This time I'm able to compile and run my code properly, but it tells me that there is a segmentation fault. Can someone help me figure out how to fix it? My code is below, thanks.

#include <stdio.h>
#include <cs50.h>
#include <string.h>

//max number of candidates
#define MAX 9

//candidates have name and vote count
typedef struct
{
    string name;
    int votes;
}
candidate;

//array of candidates
candidate candidates [MAX];

//number of candidates
int candidate_count;

//function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
    //check for invalid usage
    if(argc < 2)
    {
        printf("Usage: [candidate ...]\n");
        return 1;
    }
    
    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }

    int voter_count = get_int("Number of voters: ");

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name))
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();
}

//update vote totals given a new vote
bool vote(string name)
{
    bool got = false;
    for(int y = 0; y < candidate_count; y++)
    {
        if(strcmp(name, candidates[y].name) == 0)
        {
           candidates[y].votes += 1;

            got = true;

            break; 
        }
    }
    return got;
}

void print_winner(void)
{
    int most = 0;
    string winner;
    
    for(int j = 0; j < candidate_count; j++)
    {
        if(candidates[j].votes >= most)
        {
            most = candidates[j].votes;

            for(int x = 0; x < candidate_count; x++)
            {
                if(candidates[j].name >= winner)
                {
                    winner = candidates[j].name;
                }
            }
        }
    }
    printf("Winner is %s with %i votes\n", winner, most);

    return;
}
  • Which line is causing the seg fault? Identifying the specific line of code that throws a seg fault is a critical skill. – Cliff B Jun 30 at 7:17
  • I just started coding a few weeks ago so I'm not sure how to identify a seg fault. Is there a specific way you recommend finding them? – Aarti Jun 30 at 7:19
  • I think the segmentation fault is on the line that says printf("Winner is %s with %i votes\n", winner, most); but I'm still not sure how to fix it. Do you know how? – Aarti Jul 1 at 3:54

You must log in to answer this question.

Browse other questions tagged .