主要功能代码如下:

#define MEM_INCR 20

int main(void)
{
char *str = NULL, **s_words = NULL, *temp = NULL, *tempbuf = NULL;
int wordcount = 0, i, length = 0, memo = 0;

do
{
    if(length >= memo)
    {
        memo += MEM_INCR;
        if(!(tempbuf = realloc(str, memo)))
        {
            printf("Memory allocation failed.");
            return 1;
        }
        str = tempbuf;;
    }
}
while((str[length++] = getchar()) != '\n');
str[--length] = '\0';

wordcount = word_count(str);

s_words = malloc(wordcount); //Allocate sufficient memory to store words
for(i = 0; i < wordcount; i++) //Now allocate memory to store each word
    s_words[i] = calloc(MAX_LENGTH, sizeof(char)); //Use this function in order not to have unfilled space
segment(str, s_words); //Segment the string into words

printf("Words sorted: \n"); //Output the message
for(i = 0; i < wordcount; i++) //Short the words from the shortest to the longest
{
    if(strcmp(s_words[i], s_words[i + 1]) > 0) //Check if the first word is longer than the second
    {
        temp = s_words[i]; //Store the first address in temp
        s_words[i] = s_words[i + 1]; //Assign the successive address to the previous one
        s_words[i + 1] = temp; //Assign the first to the successive
        temp = NULL; //Ensure NULL in order to avoid leaks
    }
    printf("%s", s_words[i]); //Output the words ordered
}
return 0;
}


如果我提供了一个固定的字符串,或者如果我使用gets()函数,则该程序运行良好,但是当我使用上述代码以便能够接收任何长度的字符串时,我会崩溃。当前存在的功能正常运行,唯一的问题是使用getchar时。你能帮我吗?

提前致谢!!

最佳答案

你写了:

do {
    /* ... */
} while((str[length++] = getchar()) != '\n');


但是getchar()的定义是int getchar(void)getchar()函数被定义为有充分的理由返回int -它需要某种方式来告诉您不再有输入。那就是返回-1 -在您的代码中,如果发生这种情况,那么您的循环就会消失,gethchar()不断地不断返回-1,并且您会不断分配内存,直到全部消失。

编辑:一种可能的解决方法:

int c;

do {
    /* ... */
    c = getchar();
    if (c < 0) c = '\0';        /* one idea, handle this case as you see fit */
    if (c == '\n') c = '\0';
} while ((str[length++] = c) != '\0');

07-24 09:38
查看更多