2012-09-12 47 views
0

我想從現有的字符串中提取子字符串,但它引發了分段錯誤錯誤。它在早上執行得很好,但我不知道爲什麼它現在給出了seg錯誤請別人幫我。子字符串C程序中的分段錯誤

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

int main() 
{ 
    char str[] ="1017122,1,10,?,1,1"; 
    char * pch,*pch1; 
    FILE *fp; 
    char *str1,*str2; 
    int noofattr=0; 
    int strlen1; 

    /*if(remove("abc.txt") != 0) 
    perror("The file is successfully deleted.\n"); 
    else 
    printf("Error in deleting the file.\n"); 
*/ 

    printf ("Splitting string \"%s\" into tokens:\n",str); 
    pch = strtok (str,","); 
    while(pch!=NULL) 
    { 
      if(strcmp(pch,"?")!=0) 
      { 
       strcat(str1,pch); 
       strcat(str1,","); 
      } 
      else 
      { 
       strcat(str1,pch); 
       strcat(str1,","); 
      } 
      pch = strtok (NULL,","); 
      noofattr++; 
    } 


    strlen1=strlen(str1); 
    //memcpy(str2,&str1,strlen1-1); 
// strncpy(str1,str1+0,strlen1-1); 
    printf("\nThe formatted string is %s and its length is %d\n",str1,strlen1); 
    printf("\nThe total no. of attributes except SCN are %d\n",noofattr); 
    return 0; 
} 
+0

你有沒有試過通過gdb運行它?調試器對於解決這樣的問題是非常寶貴的。 – sonicwave

+0

不..不知道它...它是Windows調試器嗎? – Teja

+0

當得到分段錯誤或任何其他崩潰時,您的第一反應應該是在調試器中運行您的程序。它會幫助你找到崩潰的位置,並讓你檢查變量以幫助你理解崩潰的原因。 –

回答

1

str1指向內存中的隨機位置,你必須(是必須)將其設置爲足夠大,就可以嘗試一種strcat之前舉行的最後結果的緩衝器。

+0

所以我應該使用malloc分配內存? – Teja

+0

是的,像'str1 = malloc(...); strcpy(str1,「」);'應該這樣做(用計算結果長度的上限+ 1的公式替換'...') –

+0

現在它可以工作.... – Teja

0

您的str1未被分配,當然它得到段錯誤。