Thursday, April 26, 2018

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

Answer



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

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...