2016-10-22 111 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的信息。也許你應該編輯你的答案來添加這個信息。 –