因getchar而崩溃

时间:2014-09-10 19:03:45

标签: c getchar

主要功能代码如下:

#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时。你能帮帮我吗?

提前致谢!!

1 个答案:

答案 0 :(得分:-1)

您写道:

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');