I am getting a segmentation fault despite knowing that the size of the candidates[] array is the same as the value stored in the variable candidate_count and I am iterating through the array from 0 to candidate_count - 1, so how I am going out of bounds?

bool vote(string name)
    int j;
    for (j = 0; j < candidate_count; j++)
        if (strcmp(name, candidates[j].name) == 0)
            return true;
    return false;

void print_winner(void)
    int k;
    candidate winner;
    winner.name = "";
    winner.votes = 0;
    for (k = 0; k < candidate_count; k++)
        if (candidates[k].votes > winner.votes)
            strcpy(winner.name, candidates[k].name);
            winner.votes = candidates[k].votes;
    printf("%s", winner.name);

1 Answer 1


strcpy will copy the characters from one string to another location. You specify winner.name as the target, but that one currently is "". The compiler would translate "" to a string (in this case consisting of just the null terminator) that is stored in some memory that is loaded before main runs, and is read-only (so you don't accidentally overwrite other stuff).

You would have to provide the space for that string, either in the form of some char array, or memory you allocated on heap.

Instead of copying the string, you could copy the pointer, like winner.name = candidates[k].name. Or just remember the index of that candidate.

But is that really what you need? What about ties, where there are multiple winners?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .