2014-09-10 59 views
0

主要功能代码如下:崩盘的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; 
} 

程序工作正常,如果我提供给它一个固定的字符串,或者如果我用得到()函数,但是当我使用上面的代码为了能够接收任意长度的字符串,我得到了崩溃。存在的函数正常工作,唯一的问题是使用getchar时。你能帮我吗?

在此先感谢!

+1

认沽返回值,并检查错误/ EOF。尝试使用函数。避免使用“聪明”/简洁的代码,例如单独分配条件。使用调试器或调试打印(提示,你正在分配0字节,如果我看到正确)。 – hyde 2014-09-10 19:14:59

+0

1)'s_words = malloc(wordcount);' - >'s_words = malloc(wordcount * sizeof(char *));' – BLUEPIXY 2014-09-10 19:19:15

+0

2)'我' 's_words [i + 1]' – BLUEPIXY 2014-09-10 19:22:27

回答

-1

您写道:

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

getchar()的定义是int getchar(void)getchar()函数被定义为返回一个int有很好的理由 - 它需要某种方式告诉你没有更多的输入。这种方式是返回-1 - 在您的代码中,如果发生这种情况,那么您的循环会消失,gethchar()只会一直返回-1,并且一直在分配内存,直到它全部消失。

编辑:一个可能的解决办法:getchar`为`int`的`

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

你仍然有几个问题以下,其他人至少已部分解决 – 2014-09-10 19:35:59

+0

好吧,我明白了,但我怎么能实现我想要的(有任何长度的字符串),什么函数应该我用? – dim23 2014-09-10 19:36:43

+0

我上面提供的内容加上你的'if(length> = memo)...'代码(这对我来说看起来是正确的)放在我写'/ * ... * /'的地方会做到这一点。 – 2014-09-10 19:40:50