I am having a problem with a simple program that should print a histogram displaying the frequency of different characters in its input. I would try using gdb, but it is not installed on my system at the moment, and it would take forever to reinstall the compiler.
Here is the code:
#include <stdio.h>
#define MAX_CHARS 256 /* maximum number of chars to count */
/* 1-14; print a histogram showing the frequency of
characters in input */
main()
{
/* declare vars */
int c, i, j, charsmax;
int chars[MAX_CHARS];
/* initialize vars */
charsmax = 0;
for (i = 0; i < MAX_CHARS; ++i)
chars = 0;
/* get chars */
while ((c = getchar()) != EOF)
++chars[c];
/* which character appears most often? */
for (i = 0; i < MAX_CHARS; ++i)
if (chars > charsmax)
charsmax = chars;
/* now for the histogram */
for (i = charsmax; i > 0; --i) {
printf("%3d |", i);
for (j = 0; i < MAX_CHARS; ++j) {
if (chars[j] >= i)
printf(" *");
else printf(" ");
}
putchar('\n');
}
printf(" ");
for (i = 0; i < MAX_CHARS; ++i)
printf("----");
putchar('\n');
printf(" ");
for (i = 0; i < MAX_CHARS; ++i)
printf("%4d", i + 1);
putchar('\n');
}
And the output when I run it on the source file (
./a.out < charfreq.c
):
[mark@hendrix ~/code/kandr]$ ./a.out <charfreq.c
129 | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Segmentation fault
[mark@hendrix ~/code/kandr]$
I'd appreciate any help. As I said I don't have access to gdb at the moment and my efforts of reviewing the code have not been productive.
Thanks,
Mark