My pset5 speller is complete works with all check 50. Hell it's even faster then the staff's speller. BUT valgrind is not happy. I am unable to free malloc function used in check. if i do it before any return function speller fails, after return it doesn't matter. even trying to free it in unload not working.


bool check(const char* word)
    //TODO : DONE
    int m = strlen (word);
    s = malloc ((m+1)* sizof (char));

    for (int i=0; i<m ; i++)
        if(isalpha (word[i]))
            s[i] = tolower(word[i]);
            s[i] = word[i];

    int n = hash_fn(s);
    head = hashtable[n];

    if (n>=0)
        while (head != NULL)
            if (strcmp (s, head->word) == 0)
                return true;

            head = head->next;

    return false

declared char* s as global variable so that i can free it later in unload but not working at all. valgrind shows the accessible blocks at "s = malloc ....."

1 Answer 1


Well, it seems to me that if you want to free that particular malloc, you need to have two free() statements, one immediately before each return so that no matter how you exit, it gets freed. For the return true, it would have to look something like this:

    if (strcmp (s, head->word) == 0)
          return true;

If you put it before the IF statement, it blows up. I also believe this removes the need to make it global. (BTW, there's a missing ; after the return false.)

However, the better question is why you have a malloc() in check() at all? Instead of going to all that trouble, why not keep it simple and just create a string variable on the stack?

char tmpword[strlen(word)+1];
tmpword[strlen(word)] = '\0';

for(int i = 0; i<strlen(word); i++) 

If this answers your question, please click on the check to accept. Let's keep up on forum housekeeping. ;-)

  • freeing s just before return should work, and i tried that before posting here, but somehow that makes the word go unchecked no spelling errors were found. but the second solution helped, and there's no more leaks. i thought it before but was NOT sure how to pass this char array in strcmp. but after seeing your answer i found it.. thanks
    – Govinda
    Sep 22, 2015 at 19:45

You must log in to answer this question.

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