C - 分段故障核心转储?

时间:2015-01-18 04:28:26

标签: c segmentation-fault

我运行时遇到了分段故障核心转储,我不知道如何修复它。

 void removeAllCharFirstAlphaNum(FILE *fp)
 {
  // get file pointer and read the file
  char *line = NULL;
  size_t len = 0;
  ssize_t read;


     if (fp == NULL)
  {
      printf("Option b: file pointer failure\n");
      exit(EXIT_FAILURE);
  }

  printf("Option b: file pointer passed\n");
  // now read thef ile and do some cray cray stuff
  while ((read = getline(&line, &len, fp)) != -1)
  {

      unsigned int i = 0;
      char *currentChar = line;
     char *modifiedString;
      int foundAlphaNum = 0;
      // if the currentChar != ' ' && '\t' then go forward
      // otherwise skip it and move to the next char
      while ((currentChar != '\0') && (i < (read - 1)))
      {
          if (isalnum(*currentChar))
          {
              foundAlphaNum = 1;
          }

          if (*currentChar != ' ' && *currentChar != '\t' && foundAlphaNum)
          {
              modifiedString[i] = *currentChar;
              i++;
          }
          else if ((*currentChar == ' ' || *currentChar == '\t') && !foundAlphaNum)
          {
              modifiedString[i] = *currentChar;
              i++;
          }
         currentChar++;
     }

     // add null terminating char (maybe...)
     modifiedString[i] = '\0';
 }

 // might need to return the modified string back or store it as
 // a reference, but this should be it

 // need to free mem

 if (line)
     free(line);
 printf("end of option b\n");
}

1 个答案:

答案 0 :(得分:2)

while ((read = getline(&line, &len, fp)) != -1)
{

  unsigned int i = 0;
  char *currentChar = line;
  char *modifiedString; //modifiedString is NULL
  int foundAlphaNum = 0;
  // if the currentChar != ' ' && '\t' then go forward
  // otherwise skip it and move to the next char
  while ((currentChar != '\0') && (i < (read - 1)))
  {
      if (isalnum(*currentChar))
      {
          foundAlphaNum = 1;
      }

      if (*currentChar != ' ' && *currentChar != '\t' && foundAlphaNum)
      {
          modifiedString[i] = *currentChar; //and here you are trying to derefernce a NULL pointer
          i++;
      }
      else if ((*currentChar == ' ' || *currentChar == '\t') && !foundAlphaNum)
      {
          modifiedString[i] = *currentChar;
          i++;
      }
     currentChar++;
 }