简体   繁体   中英

Segmentation fault with strcmp, but the string prints using printf

I have a tokenizer method that returns a char** . The results are being stored in a char** called lineTokens . When I use printf() to print the first token, I get the correct result, but when I use strcmp(lineTokens[0],"Some text") , I get a seg fault. The appropriate code is below.

lineTokens = tokenize(tempString);
printf("token[0] = %s\n", lineTokens[0]);
if(strcmp(lineTokens[0], "INPUTVAR")==0){
    printf("It worked\n");
}

EDIT: My tokenize code is as follows

char** tokenize(char* input){
int i = 0;
char* tok;
char** ret;
tok = strtok(input, " ");
ret[0] = tok;
while(tok != NULL){
    printf("%s\n", tok);
    ret[i] = tok;
    tok = strtok(NULL, " ");
    i++;
}
ret[i] = NULL;
return ret;

}

It's impossible to answer this without seeing the code of tokenize() , of course.

My guess is that there is some undefined behavior in that function, which perhaps corrupts the stack, so that when printf() runs and actually uses some more stack space, things go bad. The thing with undefined behavior is that it's really undefined, anything can happen.

Run the code in Valgrind.

Your tokenize function is broken. Every pointer in your code needs to point at allocated memory, which is not the case here. You get no memory allocated by simply declaring a pointer: a pointer is merely containing an address to memory allocated some place else. Given that you set it to point at "some place else", if you don't, it will point at a random garbage address.

So you need to rewrite that function from scratch. Either pass a pointer to allocated memory as a parameter or allocate memory dynamically inside the function. But before you do, I would strongly recommend that you study arrays and pointers some more, for example by reading this chapter of the C FAQ.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM