Thursday, 26 April 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

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...