Plug memory leaks
This commit is contained in:
parent
1612cd1f04
commit
ceb9db2967
@ -47,11 +47,11 @@ int main() {
|
|||||||
Towels towels;
|
Towels towels;
|
||||||
towels.towels_count = 0;
|
towels.towels_count = 0;
|
||||||
towels.map = malloc(sizeof(AocHashmap));
|
towels.map = malloc(sizeof(AocHashmap));
|
||||||
|
|
||||||
for (int i = 0; i < AOC_HASHMAP_RADIX; i++) {
|
for (int i = 0; i < AOC_HASHMAP_RADIX; i++) {
|
||||||
towels.map->buckets[i] = NULL;
|
towels.map->buckets[i] = NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
line = aoc_read_line();
|
line = aoc_read_line();
|
||||||
char *token = strtok(line, ", ");
|
char *token = strtok(line, ", ");
|
||||||
while (token != NULL) {
|
while (token != NULL) {
|
||||||
@ -71,6 +71,7 @@ int main() {
|
|||||||
printf("Part 1: %d\n", valid_single_designs);
|
printf("Part 1: %d\n", valid_single_designs);
|
||||||
printf("Part 2: %ld\n", valid_multi_designs);
|
printf("Part 2: %ld\n", valid_multi_designs);
|
||||||
|
|
||||||
|
aoc_hashmap_free(towels.map);
|
||||||
aoc_free();
|
aoc_free();
|
||||||
exit(0);
|
exit(0);
|
||||||
}
|
}
|
||||||
|
@ -31,14 +31,39 @@ AocHashmapNode *aoc_hashmap_get(AocHashmap *map, char *key) {
|
|||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
void *aoc_hashmap_put(AocHashmap *map, char *key, void *value) {
|
void aoc_hashmap_put(AocHashmap *map, char *key, void *value) {
|
||||||
int hash = aoc_hash(key);
|
int hash = aoc_hash(key);
|
||||||
AocHashmapNode *node = map->buckets[hash];
|
AocHashmapNode *node = map->buckets[hash];
|
||||||
while (node != NULL) node = node->next;
|
if (node == NULL) {
|
||||||
map->buckets[hash] = malloc(sizeof(AocHashmapNode));
|
map->buckets[hash] = malloc(sizeof(AocHashmapNode));
|
||||||
node = map->buckets[hash];
|
node = map->buckets[hash];
|
||||||
node->key = malloc(strlen(key) + 1);
|
node->key = malloc(strlen(key) + 1);
|
||||||
strcpy(node->key, key);
|
strcpy(node->key, key);
|
||||||
node->value = value;
|
node->value = value;
|
||||||
node->next = NULL;
|
node->next = NULL;
|
||||||
|
} else {
|
||||||
|
AocHashmapNode *next = node->next;
|
||||||
|
while (node->next != NULL) {
|
||||||
|
node = node->next;
|
||||||
|
}
|
||||||
|
node->next = malloc(sizeof(AocHashmapNode));
|
||||||
|
node->next->key = malloc(strlen(key) + 1);
|
||||||
|
strcpy(node->next->key, key);
|
||||||
|
node->next->value = value;
|
||||||
|
node->next->next = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void aoc_hashmap_free(AocHashmap *map) {
|
||||||
|
for (int i = 0; i < AOC_HASHMAP_RADIX; i++) {
|
||||||
|
AocHashmapNode *node = map->buckets[i];
|
||||||
|
while (node != NULL) {
|
||||||
|
AocHashmapNode *next = node->next;
|
||||||
|
free(node->key);
|
||||||
|
free(node->value);
|
||||||
|
free(node);
|
||||||
|
node = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
free(map);
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user