Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help in understanding what is going on in C program

Tags:

c

So I have very weird bug that I cannot understand. I am running loop and checking for NULL value then I suppose to terminate loop. But, I am getting some EXC_BAD_ACCESS issue after I have the following values (as you can see on the screenshot)

This is additional piece of code that returns 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 that 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 have no idea why this error can occur and why. Because we can have either pointer that points somewhere or NULL value... enter image description here

like image 322
YohanRoth Avatar asked Nov 11 '22 01:11

YohanRoth


1 Answers

Your TKGetNextToken tests for a NULL that 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;
like image 197
Rich Avatar answered Nov 14 '22 23:11

Rich