2016-10-22 113 views
0

我在拆分C中的字符串时遇到了问题。每次尝试执行我的代码时,都会出现“分段错误”错误。但我不太清楚问题是什么。C - 将字符串拆分成多个部分

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

char** string_array = NULL; //string array for the split method 

    static int split_string(char* string, char* delimiter) 
    { 
     char* part = strtok(string, delimiter);//string which is getting split out by strtok 
     int number_of_parts = 0;//number of strings 

     /*split string into multiple parts*/ 
     while(part) 
     { 
      string_array = realloc(string_array, sizeof(char*)* ++number_of_parts); 

      if(string_array == NULL)//allocation failed 
       return -1; 

      string_array[number_of_parts-1] = part; 
      part = strtok(NULL, delimiter); 
     } 

     /*write final null into string_array*/ 
     string_array = realloc(string_array, sizeof(char*)* (number_of_parts+1)); 
     string_array[number_of_parts] = 0; 

     return 0; 
    } 


int main() 
{ 
    char* string = "string1 string2 string3"; 
    printf("%d", split_string(string, " ")); 
    return 0; 
} 
+0

@ n.m。同意,但OP很难找到这个参考。 –

+0

请注意,如果/当重新分配失败时,'old_ptr = realloc(old_ptr,new_size)'构造会泄漏内存。你需要使用'void * new_ptr = realloc(old_ptr,new_size); if(new_ptr == 0){...处理错误...} old_ptr = new_ptr;'。这样,你仍然在'old_ptr'中有一个有效的指针,它仍然可以被释放。 –

回答

1

strtok()写入字符串,所以你不能使用字符串作为参数。有问题的行是这一个:

char* string = "string1 string2 string3"; 

一种可能的解决方法是改变字符串从指针数组:

char string[] = "string1 string2 string3"; 

的gcc编译选项-Wwrite串警告对于这种问题。

请注意,此警告已从gcc的选项-Wdiscarded-qualifiers中删除,并且不会由-Wall -Wextra -std = c99 -pedantic。

+0

还有另一个问题:'strtok'部分需要'strdup'或者你在所有指针中都得到相同的字符串。 –

+0

只是为了记录:gcc编译器选项-Wwrite-strings警告这类问题。出于某种奇怪的原因,此警告已从-Wdiscarded限定符中删除,并且不是-Wall -Wextra -std = c99 -pedantic的一部分。奇怪的。 –

+0

这只是愚蠢的!我手动发现了这个问题,并且使用了-Wall而没有成功。 SO上有链接解释如何获得所有警告,我的意思是所有的警告? thx的信息。也许你应该编辑你的答案来添加这个信息。 –