Search code examples
cgetchar

Crash due to getchar


The main function code is as follows:

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

The program works fine if i have a fixed string supplied to it or if i use the gets() function, but when i am using the above code in order to be able and receive a string of any length i get a crash. The function that are present are working correctly, the only problem is when using getchar. Can you help me please?

Thanks in advance!!


Solution

  • You wrote:

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

    But the definition of getchar() is int getchar(void). The getchar() function is defined to return an int for good reason -- it needs some way to tell you there is no more input. That way is to return -1 -- in your code, if that happens then your loop runs away, gethchar() just keeps returning -1 over and over and over and you keep allocating memory until it is all gone.

    EDIT: One possible fix:

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