0

I am working on scrabble.c for Lab 2 and was able to compile and run the code but for some of the words, there is this error:

double free or corruption (out) Aborted (core dumped)

I tried to google for solutions of this error but still unable to solve it. Could anyone help with this? Thank you!

:) scrabble.c exists :) scrabble.c compiles :) handles letter cases correctly :) handles punctuation correctly :( correctly identifies 'Question?' and 'Question!' as a tie expected exit code 0, not None :) correctly identifies 'hai!' as winner over 'Oh,' :) correctly identifies 'COMPUTER' as winner over 'science' :) correctly identifies 'Scrabble' as winner over 'wiNNeR' :( correctly identifies 'Skating!' as winner over 'figure?' expected exit code 0, not None

Code:

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

// Points assigned to each letter of the alphabet
int POINTS[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};

int compute_score(string word);

int main(void)
{
    // Get input words from both players
    string word1 = get_string("Player 1: ");
    string word2 = get_string("Player 2: ");

    // Score both words
    int score1 = compute_score(word1);
    int score2 = compute_score(word2);

    // TODO: Print the winner
    if (score1 > score2)
    {
        printf("Player 1 wins!\n");
    }
    else if (score2 > score1)
    {
        printf("Player 2 wins!\n");
    }
    else if (score1 == score2)
    {
        printf("Tie!\n");
    }
}

int compute_score(string word)
{
    // TODO: Compute and return score for string
    int sum = 0;
    for (int i = 0, n = strlen(word); i < n; i++)
    {
        if (isupper(word[i]))
        {
            word[i - 65] = POINTS[i];
            sum = sum + POINTS[i];
        }
        else if (islower(word[i]))
        {
            word[i - 97] = POINTS[i];
            sum = sum + POINTS[i];
        }
        else
        {
            sum = sum + 0;
        }
    }
    return sum;
}

1 Answer 1

2

One problem is word[i - 65] (and here word[i - 97]). word[i] is the letter, 65 is the offset. If i is 0, and word[i] = 'a', it will try to reference word[-65]. That is invalid memory. It is an unpredictable result, so program may or may not fail.

Another problem is this word[i - 65] = POINTS[i];. This will change the value in word, which is not the desired outcome.

Finally, this sum = sum + POINTS[i]; will always add the value at POINTS[i] to sum. So the longer word will always win.

Once this word[i - 65] is corrected, it will produce the desired index in POINTS.

You must log in to answer this question.

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