2012-12-14 63 views
0

我有问题realloc。这是我的功能,它从输出中读取单词,并在检测到EOF时终止。 该函数使内存泄漏,以下程序将引发SIGSEGV或SIGABORT。什么是问题?动态指针数组realloc失败

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

你用调试器或添加了额外的'printf'语句找到该行的程序失败吗?代码示例末尾是否存在缺少“while”语句? – simonc

+0

你确定没有要阅读的单词,大于99个字符吗? – alk

+0

向malloc添加错误检查。不要投射malloc也不要realloc。 – alk

回答

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

...