【发布时间】:2015-08-02 14:22:52
【问题描述】:
我的 C 作业需要帮助。任务是编写一个程序,该程序接受长度未知的字符串输入。我还需要分隔单词,这就是我使用char** 的原因。当出现特殊单词时,程序停止输入。你可以在下面看到我的代码:
char **words=NULL;
maxWords=1;
numberOfWords=0;
words=calloc(maxWords,sizeof(char **));
input=malloc(max*sizeof(char *));
words[numberOfWords]=calloc(max,sizeof(char*));
while(stopValue){
while((c=getchar())!='\n' && c!=' ' && c!=EOF){
input[i++]=c;
if(i==currentSize){
currentSize=i+max;
input=realloc(input,currentSize);
words[numberOfWords]=realloc(words[numberOfWords],currentSize);
}
}
input[i]='\0';
if(strcmp(input,terminator)==0){
break;
}
strcpy( words[numberOfWords],input);
numberOfWords++;
maxWords++;
words=realloc(words,maxWords);
words[numberOfWords]=calloc(max,sizeof(char*));
currentSize=max;
i=0;
input=realloc(input,max);
}
当我只有 2-3 个单词的输入时,效果很好。但是当有更多时它会失败。我认为问题出在words=realloc(words,maxWords); 这一行,但我不知道具体是什么。
有什么帮助吗?
【问题讨论】:
-
为什么要重新分配单词而不是等待完整输入?为什么不只是 malloc 输入的副本?第一个输入分配在哪里?为什么在循环结束时重新分配它?
-
@RahulRaina 为什么
realloc()不能循环工作? -
对于
maxWords、numberOfWords、currentSize、max、i、@987654331 等事物的类型和值,我高度怀疑我的 猜测 @ 等,不会与您的实际运行值对齐。所以...发布MCVE -
@Ôrel 他正在读取输入,没有要复制的字符串。
-
在对
calloc的调用中使用maxWords和numberOfWords之后,您正在设置它们的值。那可能是错的。你也弄错了分配:指针不需要为自己分配空间,只为它指向的东西分配空间:Type *p = calloc(n, sizeof *p);
标签: c memory-leaks realloc