Skip to content

Commit d8c1ffc

Browse files
committed
chore: refactoring, fixing memory leaks
1 parent 48794d1 commit d8c1ffc

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

src/day1.c

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@ char *readLine(FILE *pFile);
66
int compare (const void * a, const void * b);
77
int findOccurrences(int value, const int array[1000]);
88

9-
const int MAX_LINE_LENGTH = 1000;
9+
const int MAX_FILE_ROWS = 1000;
1010

1111
int main(void) {
1212
FILE *file = fopen("data/day1.txt", "r");
1313

14-
int firsts[MAX_LINE_LENGTH];
15-
int seconds[MAX_LINE_LENGTH];
14+
int firsts[MAX_FILE_ROWS];
15+
int seconds[MAX_FILE_ROWS];
1616

1717
int ctr = 0;
1818
while (!feof(file)) {
@@ -27,19 +27,20 @@ int main(void) {
2727
seconds[ctr] = s;
2828

2929
ctr++;
30+
free(line);
3031
}
3132

32-
qsort (firsts, MAX_LINE_LENGTH, sizeof(int), compare);
33-
qsort (seconds, MAX_LINE_LENGTH, sizeof(int), compare);
33+
qsort (firsts, MAX_FILE_ROWS, sizeof(int), compare);
34+
qsort (seconds, MAX_FILE_ROWS, sizeof(int), compare);
3435

3536
int sum = 0;
36-
for (int n=0; n<MAX_LINE_LENGTH; n++)
37+
for (int n=0; n < MAX_FILE_ROWS; n++)
3738
sum += abs(firsts[n] - seconds[n]);
3839

3940
printf("Total distance: %d\n", sum);
4041

4142
sum = 0;
42-
for (int n=0; n<MAX_LINE_LENGTH; n++) {
43+
for (int n=0; n < MAX_FILE_ROWS; n++) {
4344
int first = firsts[n];
4445
int occurrences = findOccurrences(first, seconds);
4546
sum += first * occurrences;
@@ -50,10 +51,10 @@ int main(void) {
5051
return 0;
5152
}
5253

53-
int findOccurrences(int value, const int array[1000]) {
54+
int findOccurrences(int value, const int array[MAX_FILE_ROWS]) {
5455
int count = 0;
5556
if (array != NULL) {
56-
for (int i = 0; i < 1000; i++) {
57+
for (int i = 0; i < MAX_FILE_ROWS; i++) {
5758
if (array[i] == value) {
5859
count++;
5960
}

0 commit comments

Comments
 (0)