while循环中的分段错误。 Valgrind没有发现错误

时间:2018-05-05 22:01:02

标签: c malloc heap valgrind realloc

我似乎遇到了分段错误,但我无法弄清楚它出现的位置或原因。任何输入都会有所帮助。 我基本上试图将输入读作字符,将它们存储到字中直到我打到一个空格,当我点击空格时,将该字存储到wordList中。 所有这一切都必须在没有存储在内存中的情况下完成(必须使用动态分配)。

相关代码是:

  char* word;
  int WFactor = 30;
  int WLFactor = 30;
  char** wordList;
  int wordCount = 0;
  int letterCount = 0;
  word = (char*)malloc(sizeof(char) * WFactor);
  wordList = (char**)malloc(sizeof(char*) * WLFactor);

  if( word == NULL ){
    free(word);
    free(wordList);
    fprintf(stderr, "Memory Allocation Failure");
    exit(1);
  }
  if(wordList == NULL){
    fprintf(stderr, "Memory Allocation Failure");
    exit(1);
  }

  char cur = '*';
  while(cur!=EOF){ 
    if(letterCount == WFactor){
      WFactor = WFactor * 2;
      word = realloc(word, sizeof(char)*WFactor);
      if(word == NULL){

        free(word);
        free(wordList);
        fprintf(stderr, "Memory Re-Allocation Failure");
        exit(1);
      }
    }
    cur = getchar();

    if(cur!=EOF && cur!= ' '){
      putchar(cur);
      word[letterCount] = cur;
      letterCount++;
    }

    if(cur == ' '){

    if(wordCount == WLFactor){
       WLFactor = WLFactor*2;
       wordList = realloc(wordList, sizeof(char*)*WLFactor);
       if(wordList == NULL){
         free(word);
         free(wordList);
         fprintf(stderr, "Memory Re-Allocation Failure");
         exit(1);
       }
    }

    printf("%s", "e");

    wordList[wordCount] = word;
    wordCount++;
    letterCount =0;
    word = NULL;
    WFactor = 19;
    printf("HERE");
    word = malloc(sizeof(char)*WFactor);

    if(word == NULL){
      free(wordList);
      fprintf(stderr, "Memory Allocation Failure");
      exit(1);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

getchar() returns int not char

如果将结果分配给char,则无法安全地检测到^ EOF`。

修复此更改

char cur = '*';

int cur = '*';