c - Crash due to getchar -


the main function code 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;  {     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 store words for(i = 0; < wordcount; i++) //now allocate memory store each word     s_words[i] = calloc(max_length, sizeof(char)); //use function in order not have unfilled space segment(str, s_words); //segment string words  printf("words sorted: \n"); //output message for(i = 0; < wordcount; i++) //short words shortest longest {     if(strcmp(s_words[i], s_words[i + 1]) > 0) //check if first word longer second     {         temp = s_words[i]; //store first address in temp         s_words[i] = s_words[i + 1]; //assign successive address previous 1         s_words[i + 1] = temp; //assign first successive         temp = null; //ensure null in order avoid leaks     }     printf("%s", s_words[i]); //output words ordered } return 0; } 

the program works fine if have fixed string supplied or if use gets() function, when using above code in order able , receive string of length crash. function present working correctly, problem when using getchar. can me please?

thanks in advance!!

you wrote:

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

but definition of getchar() int getchar(void). getchar() function defined return int reason -- needs way tell there no more input. way return -1 -- in code, if happens loop runs away, gethchar() keeps returning -1 on , on , on , keep allocating memory until gone.

edit: 1 possible fix:

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

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -