0

我对 realloc 有问题。这是我的函数,它从输出中读取单词并在检测到 EOF 时终止。该函数导致内存泄漏,以下程序抛出 SIGSEGV 或 SIGABORT。有什么问题?

int inx=0;
char **wordList=NULL;

int v;
char tmpArr[100];

do
{
  v=scanf("%s",tmpArr);
  if(v!=-1)
  {
    char* word=(char*)malloc(strlen(tmpArr)+1);
    strcpy(word,tmpArr);
    char**more=(char**)realloc(wordList,sizeof(char*)*(inx+1));
    if(more!=NULL) {wordList=more;} else return 1;
    wordList[inx++]=word;
    printf("%d\n",inx);
  }
}
4

1 回答 1

1
v=scanf("%s",tmpArr); 

如果输入字符串大于 100,则上述内容可能会导致内存覆盖。您可能希望fgets(tmpArray,sizeof(tmpArray),stdin)改用将输入限制为最大缓冲区大小(或使用scanf_s)。

你不应该强制转换 malloc 返回的内容,它返回一个不需要强制转换的 void*,如果你强制转换,如果你忘记包含 stdlib.h,你可以掩盖错误

char* word = /* (char*) */ malloc(strlen(tmpArr)+1);

每次读取新字符串时都增加数组不是很有效,而是考虑分配一堆字符串指针或最好使用其他数据结构,例如列表

例如

if ( inx == maxindex  )
{
  char**more=(char**)realloc(wordList,sizeof(char*)*(maxindex + bunch));

  if (more != NULL) 
  {
    wordList = more;
    maxindex += bunch ;
  } 
  else 
  { 
    return 1;
  }
}

...

于 2012-12-14T10:24:03.463 回答