使用strtok()对字符串进行标记会导致c崩溃

时间:2014-05-13 14:26:03

标签: c string segmentation-fault tokenize strtok

我试图创建一个用给定的分隔符标记给定字符串的函数,将标记放在2D字符数组中并返回它。代码下方显示:

char** stringTokenizer(const char* str, const char* delims){
       char** tokens;
       size_t len = strlen(str);
       char localstr[len+1];
       int tokenslen=0;
       strcpy(localstr, str);
       tokens=malloc(sizeof(char*));

       char* tmp = strtok(localstr, delims);
       while(tmp){
                  if(++tokenslen>1) realloc(tokens, tokenslen*sizeof(char*));
                  tokens[tokenslen-1]=malloc((strlen(tmp)+1)*sizeof(char));
                  strcpy(tokens[tokenslen-1],tmp);
                  tmp = strtok(NULL, delims);
       }
       if(tokenslen==0){
                        free(tokens);
                        return NULL;

       } else return tokens;
}

当我尝试打印任何令牌时[i]即将崩溃。

只要有一个令牌,我就会增加令牌数组的大小,并为要复制的令牌分配指针。

有什么建议吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试这样做

char** stringTokenizer(const char* str, const char* delims){
       char** tokens = NULL;
       size_t len = strlen(str);
       char localstr[len+1];
       int tokenslen=0;
    char **temp;//Change
       strcpy(localstr, str);

       //tokens=malloc(sizeof(char*));

       char* tmp = strtok(localstr, delims);
       while(tmp){
                  //if(++tokenslen>1) realloc(tokens, tokenslen*sizeof(char*));
    temp = realloc(tokens, tokenslen*sizeof(char*));
    tokens = temp;
                  tokens[tokenslen-1]=malloc((strlen(tmp)+1)*sizeof(char));
                  strcpy(tokens[tokenslen-1],tmp);
                  tmp = strtok(NULL, delims);
       }
       /*if(tokenslen==0){
                        free(tokens);
                        return NULL;

       } else*/ return tokens;
}

谢谢@netcoder