简体   繁体   中英

C Strtok Segfaulting

I'm not sure why the following code is segfaulting:

char * buffer = "SIZE";
char * tempString;
tempString = strtok(buffer, " ");
if(strcmp(tempString, "SIZE") == 0){    
    tempString = strtok(NULL, " ");           <----Faulting here
}

Since there is nothing left to tokenate shouldn't tempString just be equal to NULL? Thank you for any help in advance.

There are two problems:

First, strtok requires a modifiable string for the first parameter and buffer in your example is not. Try this instead:

char buffer[] = "SIZE";

Second, strcmp doesn't handle NULL which strtok can return:

if (NULL != tempString && strcmp(tempString, "SIZE") == 0)

Just go over the tokenized elements as the reference says , you have a clean approach if you follow it.

CORRECT CODE:

char buffer[] = "SIZE";
char * tok;
tok = strtok(buffer, " ");
while(tok != NULL)
{
  if(strcmp(tok, "SIZE") != 0)    
    break;
  tok = strtok(NULL, " ");        //   <----Faulted here
}

yes, it may skip multiple "SIZE" words in the buffer, so it does a bit more than what you originally did, but it is easier to read for an other programmer (and easier to recall it later, for you too).

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