简体   繁体   中英

C program freezes for word lengths greater than 6

I'm working through the first chapter of K&R and came to the exercise where you're supposed to create a histogram of word lengths for some input. I started by trying to use a while loop to create an array of zeros as long as the longest word, but inputs with words longer than six characters cause the program to freeze. I'm less interested in just a solution than I am in knowing the cause.

#include <stdio.h>

main()
{
int c, i, l, max;
int length[max];

l = max = 0;

    while((c = getchar()) != EOF){
        if(c != ' ' && c != '\t' && c != '\n'){
            ++l;
            if(l > max)
               max = l;
             else
                 ;
             }
        else
            l = 0;
        }
    for(i = 0; i < max; ++i)
        length[i] = 0;

    for(i = 0; i < max; ++i)    
        printf("\n%d", length[i]);
        putchar('\n');
}

max is uninitialized when length[max] is defined. Essentially, you're using unallocated memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM