Segmentation Fault when using strtok_r

后端 未结 6 956
野的像风
野的像风 2020-12-14 02:55

Can anyone explain why I am getting segmentation fault in the following example?

#include 
#include 

int main(void) {
  char          


        
6条回答
  •  有刺的猬
    2020-12-14 03:42

    A bunch of things wrong:

    1. hello points to a string literal, which must be treated as immutable. (It could live in read-only memory.) Since strtok_r mutates its argument string, you can't use hello with it.

    2. You call strtok_r only once and don't initialize your tokens array to point to anything.

    Try this:

    #include 
    #include 
    
    int main(void) {
      char hello[] = "Hello World, Let me live.";
      char *p = hello;
      char *tokens[50];
      int i = 0;
    
      while (i < 50) {
         tokens[i] = strtok_r(p, " ,", &p);
         if (tokens[i] == NULL) {
            break;
         }
         i++;
      }
    
      i = 0;
      while (i < 5) {
        printf("%s\n", tokens[i++]);
      }
    
      return 0;
    }
    

提交回复
热议问题