从C中的文本文件中提取随机字时的分段错误

时间:2015-01-16 07:25:46

标签: 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[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;
}

我检查了调试器,我得到一个seg错误的行是:

*pch1 = '\0';

知道我做错了什么?

编辑:

here is the debug output after adding if(pach1) statementProgram received signal SIGSEGV, Segmentation fault.
0x00007fff906e4172 in strlen () from /usr/lib/system/libsystem_c.dylib
(gdb) where
#0  0x00007fff906e4172 in strlen () from /usr/lib/system/libsystem_c.dylib
#1  0x00007fff906f4564 in stpcpy () from /usr/lib/system/libsystem_c.dylib
#2  0x00007fff90766fb7 in __strcpy_chk ()
   from /usr/lib/system/libsystem_c.dylib
#3  0x0000000100000c77 in main (argc=2, argv=0x7fff5fbffcc8)
    at randWordSelector.c:52

添加了这些更改并尝试了#34;尝试:&#34;在goto语句的for循环顶部,现在一切正常,这里是代码

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

1 个答案:

答案 0 :(得分:2)

更改

printf("pch1 %s", pch1);
*pch1 = '\0';

if (pch1) {
     printf("pch1 %s", pch1);
     *pch1 = '\0';
}

如果在给定字符串中找不到strchr' '可能会返回NULL。

编辑: 将strcpy(new_str, pch);更改为

if (pch)
    strcpy(new_str, pch);