Need help understanding what's happening in program C

So, I have a very strange error that I cannot understand. I run the loop and check the NULL value, then I assume to end the loop. But I get some problem with EXC_BAD_ACCESS after I have the following values ​​(as you can see in the screenshot)

This is an additional piece of code that returns a char string

char *TKGetNextToken(TokenizerT *tk) { if((*tk).currentToken) return *(*tk).currentToken++; else return NULL; } 

and actual structure

 struct TokenizerT_ { char **currentToken; char **tokens; }tokenizer; 

And this is what I have for my pointers:

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

I do not know why this error can occur and why. Since we can have a pointer that points somewhere, or a NULL value ... enter image description here

+5
source share
2 answers

The TKGetNextToken test for NULL, which is never present. Add a NULL entry at the end:

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

Ok I fixed my code thanks to Joachim and JosEdu. words = (char **) malloc (sizeof (char *) * numberOfWords); numberOfWords + 1 is required because when I go outside and check for a null value, it just has some allocated memory, and I have problems.

0
source

Source: https://habr.com/ru/post/1202460/


All Articles