C: 双指针的 Realloc 问题

C: Realloc issues with double pointer

我正在尝试将 char word[50] 数组复制到 char **wordlist 双指针,然后 realloc(wordlist, (numwords+1)*sizeof(char*)) 将单词列表的大小再增加一个 char* 以保存下一个 word.

我一直收到 *** glibc detected *** ./program: realloc(): invalid next size 错误

我声明为wordlist = realloc(wordlist, (numwords+1)*sizeof(char*))

void outFile(char *argv[], char **wordlist)
  {
      if((inFilePtr = fopen(argv[2], "r")) != NULL)
      {
          if((outFilePtr = fopen(endOfFile, "w")) != NULL)
          {
              while((c = fgetc(inFilePtr)) != EOF)
              {
                  if(!(isspace(c)))
                  {
                      word[wordIndex] = c;
                      wordIndex++;
                      rowLim++;
                  }
                  if(isspace(c))
                  {
                      wordIndex = 0;
                      if(rowLim < limit)
                      {
                          rowLim++;
                          strcat(text[rowNum], word);
                          strcat(text[rowNum], " [=10=]");
                          wordlist[numwords] = strdup(word);
                          /*strcat(wordlist[numwords], "\n[=10=]");*/
                          memset(word, 0, 50);
                          prev = rowLim;
                          wordlist = realloc(wordlist, (numwords + 1)*sizeof(char*));
                          numwords++;
                      }
                      else
                      {
                          strcat(text[rowNum], "\n[=10=]");
                          printf("text[%d] = %s",rowNum, text[rowNum]);
                          fputs(text[rowNum], outFilePtr);
                          rowNum++;
                          strcat(text[rowNum], word);
                          strcat(text[rowNum], " [=10=]");
                          /*strcat(wordlist[numwords], word);
                          strcat(wordlist[numwords], "\n[=10=]");
                          wordlist = realloc(wordlist, (numwords + 1)*sizeof(char*));*/
                         numwords++;
                         memset(word, 0, 50);
                         rowLim = rowLim - prev;
                     }
                     wordIndex = 0;
                 }
             }
             strcat(text[rowNum], "\n[=10=]");
             printf("text[%d] = %s",rowNum, text[rowNum]);
             fputs(text[rowNum], outFilePtr);
             fclose(outFilePtr);
         }

您在分配 space 之前尝试使用它:

wordlist[numwords] = strdup(word);
wordlist = realloc(wordlist, (numwords + 1)*sizeof(char*));
numwords++;

相反,先分配 space:

wordlist = realloc(wordlist, (numwords + 1)*sizeof(char*));
wordlist[numwords] = strdup(word);
numwords++;

注意。正如 iharob 所指出的,如果您希望能够从 运行 内存不足中恢复,那么 realloc 的 return 值应该存储在一个单独的变量中,直到您确认它不是 NULL.

你所有的[=14=]都是多余的。字符串文字是字符串:例如 "\n" 表示已经 { '\n', '[=16=]' }

从这段代码中无法判断您是否因向 text[rowNum] 写入过多内容而导致缓冲区溢出。我建议重新设计此代码以确保它永远不会溢出。