2
votes

So basically I cannot figure out what is the problem in my code when I try to free memory for allocated char**. I created char** then allocated memory for it, then I assigned pointer to this char** to the member of my struct. When I am trying to free memory using struct member's pointer I am getting error: malloc: error for object 0x796568796568: pointer being freed was not allocated*

Here are some parts of the code:

Struct part:
struct TokenizerT_ {
    char **currentToken;
    char **tokens;
}tokenizer;

Allocation part (done in separate function):

char **words;
    words = (char **)malloc(sizeof(char*) * (numberOfWords + 1));
    for (int i = 0; i < numberOfWords; i++)
        words[i] = (char *)malloc(strlen(ts)+1);


tokenizer.tokens = words;
tokenizer.currentToken = words;

Freeing part:

int i = 0;
while(*(*tk).tokens){
    free((*tk).tokens[i]);
    i++;
}

free((*tk).tokens);
2
What's the while condition of the freeing part supposed to accomplish?humodz
just to free allocated memory that was given to **wordsYohanRoth
I was talking about the condition, not the loop itself. The way you wrote it, the condition will have the same value after every iteration, since *(*tk).tokens never changes. It's equivalent to while(tk->tokens[0] != NULL).humodz

2 Answers

2
votes

First you should realize that *(*tk).tokens is equivalent to (*tk).tokens[0]. So your loop always checks the same element as stop condition (and that element is not set to NULL after being freed so the condition continues to be true).

If you wish to stop the deallocation loop with a NULL pointer check, you'd first need to make sure the last element of words is assigned NULL. Now memory allocated by malloc is not initialized, so you would need to explicitly initialize the last element with:

words[numberOfWords] = NULL;

Then later when deallocating, you would need to update your loop stop condition to something like:

int i = 0;
while((*tk).tokens[i]){
    free((*tk).tokens[i]);
    i++;
}
free((*tk).tokens);
1
votes

Add "words[i] = 0;" to the assigning part, to make your while loop stop?

for (int i = 0; i < numberOfWords; i++)
    words[i] = (char *)malloc(strlen(ts)+1);
words[i] = 0;