0

I think the biggest issue is at the beginning of check. In the first example, I tried altering its declaration (I know I shouldn't) and since words is not a constant anymore, it gets modified by tolower and I therefore fail check50. But at least I get only 3 errors with valgrind.

bool check(char* word)
{
    int word_length = strlen(word);    
    char* hash_word = word;

    for (int i = 0; i < word_length; i++)
    {
        if (isupper(word[i]))
        {
            hash_word[i] = tolower(word[i]);
        }
        else
        {
            hash_word[i] = word[i];
        }
    }

    [...]
}

The second example below shows a different approach. I pass check50 successfully but I get hundreds of thousands of errors in valgrind's ERROR SUMMARY like

line 49: Address 0x55fbfc4 is 0 bytes after a block of size 4 alloc'd

or Uninitialised value was created by a heap allocation

bool check(const char* word)
{
    int word_length = strlen(word);
    char* hash_word = NULL;
    hash_word = malloc(sizeof(word_length)); //this is line 49

    for (int i = 0; i < word_length; i++)
    {
        if (isupper(word[i]))
        {
            hash_word[i] = tolower(word[i]);
        }
        else
        {
            hash_word[i] = word[i];
        }
    }
    [...]
}

How should I go about finding the right approach? I tried other approaches but I end up with the same results: check50 green, valgrind "red".

2

Can't tell you exactly what's happening without seeing your entire code, but one thing I can tell you right away is that you're forgetting to allocate space for the null terminator when you only malloc the strlen, like this hash_word = malloc(sizeof(word_length));.

You should malloc strlen + 1.

And note that sizeof(word_length) will give you back the size of an integer. What you really wanted to use was malloc(word_length + 1);

1
  • 1
    It went from 289564 errors to just 25 from 3 contexts only! And above all: All heap blocks were freed -- no leaks are possible. Thank you Yuri! Now I'm trying to understand the cause of the remaining errors. – Alberto Nov 11 '16 at 21:29

You must log in to answer this question.

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