1

When running a finished speller, I receive an unhelpful segmentation fault.

jharvard@appliance (~/Desktop/pset6): ./speller ~cs50/pset6/texts/austinpowers.txt
Segmentation fault (core dumped)
jharvard@appliance (~/Desktop/pset6):

I am reluctant to post my code here as someone could copy it - but if anyone has ideas or thinks exploring further could yield an answer, post a comment.

EDIT: After fixing 2 mis-mallocations the situation improved slightly.

jharvard@appliance (~/Desktop/pset6): ./speller ~cs50/pset6/texts/austinpowers.txt

MISSPELLED WORDS

Segmentation fault (core dumped)
jharvard@appliance (~/Desktop/pset6):

EDIT 2: Valgrind returned:

==19989== Conditional jump or move depends on uninitialised value(s)
==19989==    at 0x4DC2ED7B: tolower (ctype.c:46)
==19989==    by 0x804904C: check (dictionary.c:42)
==19989==    by 0x8048B6D: main (speller.c:117)
==19989== 
==19989== Use of uninitialised value of size 4
==19989==    at 0x4DC2ED8B: tolower (ctype.c:46)
==19989==    by 0x804904C: check (dictionary.c:42)
==19989==    by 0x8048B6D: main (speller.c:117)
==19989== 

Anyone know what that means?

dictionary.c:42, inside the check function where I make inputs lowercase:

char checkw[strlen(word)];
// to lowercase
for(int i = 0; i < strlen(word); i++){
    checkw[i] = tolower(checkw[i]);
}

That's the code returning the error, but I can't find anything wrong with it.

2
  • 1
    segmentation faults occurs when you touching a place in memory you don't have access to. Usually on the pset persons then to try to access a node that they have not allocated memory for or try to access an element beyond the size of an array. Commented Dec 31, 2014 at 20:20
  • aah. Looking over the code now Commented Dec 31, 2014 at 20:45

1 Answer 1

2

Make the array checkw the size of the global variable LENGTH + 1 to ensure you have an array that can hold all words. Also create a variable to store the length of word, repetitive calls to strlen is bad practice.

So your code should look like such:

char checkw[LENGTH + 1];
int len = strlen(word);
for (int i = 0; i < len; ++i)
    {
        checkw[i] = tolower(word[i]);
    }
checkw[len] = '\0';

You must log in to answer this question.

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