主要功能代码如下:崩盘的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时。你能帮我吗?
在此先感谢!
认沽返回值,并检查错误/ EOF。尝试使用函数。避免使用“聪明”/简洁的代码,例如单独分配条件。使用调试器或调试打印(提示,你正在分配0字节,如果我看到正确)。 – hyde 2014-09-10 19:14:59
1)'s_words = malloc(wordcount);' - >'s_words = malloc(wordcount * sizeof(char *));' – BLUEPIXY 2014-09-10 19:19:15
2)'我' 's_words [i + 1]' –
BLUEPIXY
2014-09-10 19:22:27