commit 44c3ec6704fffe14ab0f7bef8367a7ababa12f60
parent ce8461f31a92eb9a5988450303db8337a8864406
Author: phoebos <ben@bvnf.space>
Date: Mon, 21 Mar 2022 15:58:56 +0000
fix and free
Diffstat:
M | freq.c | | | 22 | ++++++++++++++++------ |
1 file changed, 16 insertions(+), 6 deletions(-)
diff --git a/freq.c b/freq.c
@@ -36,7 +36,7 @@ update_record(char *name) {
exit(1);
}
cs[cs_len - 1].name = strdup(name);
- cs[cs_len - 1].name = 0;
+ cs[cs_len - 1].freq = 1;
} else {
/* add 1 to freq */
cs[i].freq++;
@@ -44,9 +44,16 @@ update_record(char *name) {
}
void
+free_freqs(void) {
+ for (size_t i = 0; i < cs_len; i++)
+ free(cs[i].name);
+ free(cs);
+}
+
+void
print_freqs(void) {
for (size_t i = 0; i < cs_len; i++)
- printf("%d %s\n", cs[i].freq, cs[i].name);
+ printf("%d\t%s\n", cs[i].freq, cs[i].name);
}
int
@@ -78,6 +85,7 @@ main (int argc, char **argv) {
freq(f, field);
+
if (f != stdin)
fclose(f);
return 0;
@@ -88,14 +96,15 @@ freq(FILE *f, int field) {
char *line = NULL;
size_t linelen = 0;
ssize_t n;
- int cur_field = 1;
- int in_word = 0;
+ int cur_field, in_word;
while ((n = getline(&line, &linelen, f)) != -1) {
ssize_t i = 0;
char *field_start = line;
+ in_word = cur_field = 0;
/* eat up whitespace at front */
- while (isspace(line[i++]));
+ while (isspace(line[i]))
+ i++;
for (; i < n; i++) {
if (isspace(line[i])) {
if (in_word) {
@@ -113,11 +122,12 @@ freq(FILE *f, int field) {
}
}
field_found:
- fprintf(stderr, "found '%s'\n", field_start);
+ //fprintf(stderr, "found '%s'\n", field_start);
update_record(field_start);
}
free(line);
print_freqs();
+ free_freqs();
}