动态指针数组realloc失败

时间:2012-12-14 09:10:52

标签: c realloc

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

1 个答案:

答案 0 :(得分:1)

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

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

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

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

每次读取新字符串时生成数组都不是很有效,而是考虑分配一堆字符串指针或者最好使用其他数据结构,例如:一个清单

e.g。

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

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

...