我似乎遇到了段错误,但我无法弄清楚它发生的位置或原因。任何输入都会有帮助。 我基本上试图将输入读取为字符,将它们存储到单词中,直到我点击空格,当我点击空格时,将该单词存储到单词列表中。 所有这些都必须在不存储在内存中的情况下完成(必须使用动态分配)。
相关代码为:
char* word;
int WFactor = 30;
int WLFactor = 30;
char** wordList;
int wordCount = 0;
int letterCount = 0;
word = (char*)malloc(sizeof(char) * WFactor);
wordList = (char**)malloc(sizeof(char*) * WLFactor);
if( word == NULL ){
free(word);
free(wordList);
fprintf(stderr, "Memory Allocation Failure");
exit(1);
}
if(wordList == NULL){
fprintf(stderr, "Memory Allocation Failure");
exit(1);
}
char cur = '*';
while(cur!=EOF){
if(letterCount == WFactor){
WFactor = WFactor * 2;
word = realloc(word, sizeof(char)*WFactor);
if(word == NULL){
free(word);
free(wordList);
fprintf(stderr, "Memory Re-Allocation Failure");
exit(1);
}
}
cur = getchar();
if(cur!=EOF && cur!= ' '){
putchar(cur);
word[letterCount] = cur;
letterCount++;
}
if(cur == ' '){
if(wordCount == WLFactor){
WLFactor = WLFactor*2;
wordList = realloc(wordList, sizeof(char*)*WLFactor);
if(wordList == NULL){
free(word);
free(wordList);
fprintf(stderr, "Memory Re-Allocation Failure");
exit(1);
}
}
printf("%s", "e");
wordList[wordCount] = word;
wordCount++;
letterCount =0;
word = NULL;
WFactor = 19;
printf("HERE");
word = malloc(sizeof(char)*WFactor);
if(word == NULL){
free(wordList);
fprintf(stderr, "Memory Allocation Failure");
exit(1);
}
}
}
最佳答案
getchar()
returns int
not char
.
如果将其结果分配给 char
,则无法安全地检测 ^EOF`。
修复此更改
char cur = '*';
成为
int cur = '*';
关于c - while 循环中出现段错误。 Valgrind 没有发现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50194390/