c - while 循环中出现段错误。 Valgrind 没有发现错误

标签 c malloc heap-memory valgrind realloc

我似乎遇到了段错误,但我无法弄清楚它发生的位置或原因。任何输入都会有帮助。 我基本上试图将输入读取为字符,将它们存储到单词中,直到我点击空格,当我点击空格时,将该单词存储到单词列表中。 所有这些都必须在不存储在内存中的情况下完成(必须使用动态分配)。

相关代码为:

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

最佳答案

getchar() returns int not char .

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

修复此更改

char cur = '*';

成为

int cur = '*';

关于c - while 循环中出现段错误。 Valgrind 没有发现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50194390/

相关文章:

java - 从堆转储文件中识别堆内存的大小?

c - 在 c 中检索有符号 long long 的最高有效 32 位

c - 为什么 Knuth 使用这种笨拙的减量?

c - 我怎么知道数组中的元素是否存在?

c++ - 如何创建随机内存分配失败?

c++ - x64 free 性能低下

c - 内存不足杀死

c - Visual C 强制未使用的导入,由库拉入

c - 整数数组的动态内存分配

C 警告 : Function returns address of local variable