YohanRoth
YohanRoth

Reputation: 3263

Need help to produce correct syntax to free memory for char** when pointer to allocated memory was assign to structure member

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);

Upvotes: 2

Views: 129

Answers (2)

SleuthEye
SleuthEye

Reputation: 14577

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);

Upvotes: 2

n5c
n5c

Reputation: 136

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;

Upvotes: 1

Related Questions