C运行时错误“分段错误”-如何将其删除?

时间:2019-10-16 14:02:29

标签: c segmentation-fault clang

我不确定为什么我的代码中出现分段错误。但是,我知道它发生在while(*word == *grid_char)块中。我也尝试删除其中的代码,看看会发生什么,但仍然收到分段错误错误。但是,如果我完全删除了while循环,该错误将消失。

我知道什么是段错误,但我不明白为什么在这种情况下会出现错误。我也不知道如何调试它。

这是我的代码。

  char grid[(MAX_DIM_SIZE + 1) * MAX_DIM_SIZE + 1];
  char dictionary[MAX_DICTIONARY_WORDS * (MAX_WORD_SIZE + 1 ) + 1 ];
  int dictionary_idx[MAX_DICTIONARY_WORDS];

  char *grid_char;
  char *match_word;

  int grid_idx = 0;
  char *word = dictionary + dictionary_idx[0];
  int word_found = 0;
  int max_grid_height = row; // max y (max_grid_height) on grid
  int row = 0;
  int grid_clm = 0;

  // print_char(grid[18]);

  while (grid[grid_clm] != '\n')
  {
    row = 0;

    while(row < max_grid_height)
    {
      word = dictionary + dictionary_idx[0]; //first char from dictionary ***


      while(*word != '\0')
      {

        // print_char(*word);

        int match_row = row; // back to start point grid - using this to compare potential match
        match_word = word; // back to start point dict - using this to compare potential match

        grid_char = grid[grid_clm + max_grid_length*match_row];

        print_char(grid_char);
        print_char(*word);
        print_char(*(match_word+1));
        print_char(' ');

        while(*word == *grid_char)
        {
          match_row++;
          match_word++;

          if ((*match_word == '\n' || *match_word == '\0'))
          {
            print_char('F');
            continue;
          }
          if(match_row >= max_grid_height){
            break;
          }

          grid_char = grid[grid_clm + max_grid_length*match_row];
        }

        // next dictionary word
        while(*word != '\n' && *word != '\0'){
          word++;

        }
        if (*word == '\0'){
          break;
        }
        word++;
        // print_char(' ');

      }
      row++; //next grid row
    }
    grid_clm++; //next grid column
  }

1 个答案:

答案 0 :(得分:0)

我认为问题在于char指针grid_char的初始化,您正在分配char值而不是内存地址。