子串C程序中的分段错误

时间:2012-09-12 06:05:58

标签: c string segmentation-fault

我正在尝试从现有的字符串中提取子字符串。但它会引发我的分段错误错误。它在早上执行正常,但我不知道为什么它现在给出了seg错误。请有人帮助我。

#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;
}

2 个答案:

答案 0 :(得分:1)

str1指向内存中的随机位置,您必须(是的)必须将其设置为足够大的缓冲区,以便在尝试strcat之前保留最终结果。

答案 1 :(得分:0)

您的str1未分配,当然它会出现段错误。