C语言中从文本文件中提取随机词时出现的分词错误

C语言中从文本文件中提取随机词时出现的分词错误,c,segmentation-fault,C,Segmentation Fault,我正在写一个程序,从C语言的文本文件中提取30个随机单词。但是我遇到了seg错误,我不知道为什么。 这是我的密码: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int main(int argc, char** argv) { char str[100], new_str[100], new_str2[100], new_str3[1

我正在写一个程序,从C语言的文本文件中提取30个随机单词。但是我遇到了seg错误,我不知道为什么。 这是我的密码:

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

int main(int argc, char** argv)
{
  char str[100], new_str[100], new_str2[100], new_str3[100];
  char* pch;
  char* pch1, pch2;
  FILE* fp = fopen(argv[1], "r");
  int size = 30, str_pos = 0, str_num = 0, c = 0, str_size = 15;
  char buf[100];
  char arr[30][100];

  if(fp == NULL)
  {
    perror("The following error occured");
    exit(-1);
  }

  for (int i = 0; i < 30; i++)
  {
    srand(time(NULL)+i);

    str_num = rand() % size;


    // skip n strings
      while (str_num > 0)
      {
          fgets(buf, 100, fp);
          str_num--;
      }

    srand(time(NULL)+str_num);

    str_pos = rand() % str_size;

    // get the string
    if( fgets(str, 100, fp) != NULL)
    {
      // move str over n places
      pch = str + str_pos;
      pch = strchr(pch,' ');
      strcpy(new_str, pch);  //New SEG FAULT
      pch = new_str;         
      pch1 = strchr(pch+1,' ');
      printf("pch1 %s", pch1);

      *pch1 = '\0';  //SEG FAULT occurs here

      strcpy(new_str2,new_str);
    }
    else
    {
      fgets(str,100,fp);
    }

    strcpy(arr[i],new_str2);

    for (int i =0; i < 100; i++)
    {
      str[i]= 0; new_str[i]=0; new_str2[i]=0; buf[i]=0;
    }

    pch = 0; pch1 = 0; 

    rewind(fp);
  }

  fclose(fp);

  for (int i = 0; i < 30; i++)
  {
    printf("\t%s\n",arr[i]);
  }

  return 0;
}
知道我做错了什么吗

编辑:

在goto语句的for循环顶部添加了这些更改和一个“tryagain:”,现在一切正常,下面是代码

      if (pch)
      {   
        strcpy(new_str, pch);
        pch = new_str;
      }   
      else
      {   
        goto tryagain;
      }   

      pch1 = strchr(pch+1,' ');

      if (pch1)
      {   
        *pch1 = '\0';
        strcpy(new_str2,new_str);
      }   
      else
      {   
        goto tryagain;
      } 
改变

如果在给定字符串中找不到
'
,则As
strchr
可能返回NULL

编辑: 改变
strcpy(新的_str,pch)

if (pch)
    strcpy(new_str, pch);

这就是我用来找出seg故障发生的地方我试了你的建议,不幸的是,我仍然得到seg故障,但是,不像以前那么频繁。现在seg故障一定来自其他线路。检查它是哪一行?我添加了调试输出作为一个编辑,它说52,但52是strcpy,就在itI上面。我在strcpy()中添加了注释,现在抛出seg错误,知道为什么吗?在编辑下添加了更改。
      if (pch)
      {   
        strcpy(new_str, pch);
        pch = new_str;
      }   
      else
      {   
        goto tryagain;
      }   

      pch1 = strchr(pch+1,' ');

      if (pch1)
      {   
        *pch1 = '\0';
        strcpy(new_str2,new_str);
      }   
      else
      {   
        goto tryagain;
      } 
printf("pch1 %s", pch1);
*pch1 = '\0';
if (pch1) {
     printf("pch1 %s", pch1);
     *pch1 = '\0';
}
if (pch)
    strcpy(new_str, pch);