No memory leaks anymore

This commit is contained in:
Ano-sys
2025-02-02 16:51:59 +01:00
parent 7f6d6c1479
commit 02c31d009e
60 changed files with 474261 additions and 57129 deletions
+54 -12
View File
@@ -106,7 +106,7 @@ void free_key_value_pairs(key_value_pair **head, key_value_pair **tail)
// adds given key_value_pair to list
int add_key_value_pair(key_value_pair *kv, key_value_pair **head, key_value_pair **tail)
int add_key_value_pair(key_value_pair *kv, key_value_pair **head, key_value_pair **tail, bool concat)
{
if (!head || !*head)
{
@@ -116,24 +116,40 @@ int add_key_value_pair(key_value_pair *kv, key_value_pair **head, key_value_pair
else
{
key_value_pair *iterator = *head;
while (iterator->next != NULL)
key_value_pair *prev = iterator;
while (iterator != NULL)
{
if (strcmp(kv->key, iterator->key) == 0)
{
char *bak = iterator->value;
iterator->value = (char*)realloc(iterator->value, strlen(iterator->value) + strlen(kv->value) + 1);
if (iterator->value == NULL)
{
iterator->value = bak;
return -1;
if(concat){
char *bak = iterator->value;
iterator->value = (char*)realloc(iterator->value, strlen(iterator->value) + strlen(kv->value) + 1);
if (iterator->value == NULL)
{
iterator->value = bak;
return -1;
}
strcat(iterator->value, kv->value);
free_key_value_pair(&kv);
}
else{
long sum = atol(iterator->value) + atol(kv->value);
char buffer[32];
snprintf(buffer, sizeof(buffer), "%ld", sum);
char *tmp = realloc(iterator->value, strlen(buffer) + 1);
if (!tmp) {
return -1;
}
iterator->value = tmp;
strcpy(iterator->value, buffer);
free_key_value_pair(&kv);
}
strcat(iterator->value, kv->value);
free_key_value_pair(&kv);
return 0;
}
prev = iterator;
iterator = iterator->next;
}
iterator->next = kv;
prev->next = kv;
*tail = kv;
}
return 0;
@@ -165,6 +181,32 @@ void remove_key_value_pair(key_value_pair *kv, key_value_pair **head, key_value_
}
}
void defragment_key_value_pairs(key_value_pair **head, key_value_pair **tail){
if(!head || !*head || !tail || !*tail) return;
key_value_pair *slow_it = *head;
while(slow_it){
key_value_pair *prev = slow_it;
slow_it = slow_it->next;
key_value_pair *fast_it = slow_it;
while(fast_it){
if(strcmp(prev->key, fast_it->key) == 0){
remove_key_value_pair(prev, head, tail);
int toInsertValue = (int)atol(prev->value);
int toAddOnValue = (int)atol(fast_it->value);
char value[16];
snprintf(value, 16, "%d", toInsertValue + toAddOnValue);
free(fast_it->value);
fast_it->value = strdup(value);
free_key_value_pair(&prev);
}
fast_it = fast_it->next;
}
}
}
void extract_key_value_pairs(char *red_str, key_value_pair **head, key_value_pair **tail, bool doReduce){
char *it = red_str;
bool reading_value = false;
@@ -186,7 +228,7 @@ void extract_key_value_pairs(char *red_str, key_value_pair **head, key_value_pai
}
key_value_pair *kv = init_key_value_pair(key, value);
add_key_value_pair(kv, head, tail);
add_key_value_pair(kv, head, tail, doReduce);
// reset
word_length = 0;