1
0
Fork 0

Fixed memory allocation for addrbook_t. Ditched a separate init function and moved allocation to add func. Added a variable to store the capacity of an array.

This commit is contained in:
Alexander Andreev 2024-03-28 17:52:14 +04:00
parent c468363efb
commit a2e0694efc
Signed by: Arav
GPG Key ID: 25969B23DCB5CA34
2 changed files with 18 additions and 16 deletions

View File

@ -37,14 +37,6 @@ int addrbook_entry_from_string(addrbook_entry_t *const ent, char * str) {
return 0;
}
int addrbook_init(addrbook_t *const ab) {
ab->entries = (addrbook_entry_t *)malloc(sizeof(addrbook_entry_t));
if (ab->entries == NULL)
return -1;
ab->entries_len = 0;
return 0;
}
void addrbook_destroy(addrbook_t *const ab) {
free(ab->entries);
ab->entries_len = 0;
@ -64,6 +56,7 @@ int addrbook_load(addrbook_t *ab, FILE *in) {
if (ab->entries == NULL)
return -1;
ab->entries_len = 0;
ab->entries_cap = lines;
fseek(in, 0, SEEK_SET);
@ -94,19 +87,28 @@ int addrbook_store(addrbook_t *ab, FILE *out) {
}
int addrbook_add(addrbook_t *const ab, const addrbook_entry_t *const ent) {
if (addrbook_get(ab, ent->pubk) != NULL)
if (ab->entries == NULL) {
ab->entries = (addrbook_entry_t *)malloc(sizeof(addrbook_entry_t));
ab->entries_cap = 1;
ab->entries_len = 0;
} else if (addrbook_get(ab, ent->pubk) != NULL)
return -1;
if (ab->entries_len > 0)
ab->entries = realloc(ab->entries, ++ab->entries_len);
else
++ab->entries_len;
ab->entries[ab->entries_len-1] = *ent;
if (ab->entries_len == ab->entries_cap)
ab->entries = realloc(ab->entries, ++ab->entries_cap);
ab->entries[ab->entries_len++] = *ent;
return 0;
}
addrbook_entry_t *addrbook_get(const addrbook_t *const ab, const char pkey[CRYPT_PKEY_HEXLEN]) {
if (ab->entries == NULL)
return NULL;
for (size_t i = 0; i < ab->entries_len; ++i)
if (strncmp(ab->entries[i].pubk, pkey, CRYPT_PKEY_HEXLEN) == 0)
return &ab->entries[i];
return NULL;
}

View File

@ -23,13 +23,13 @@ int addrbook_entry_from_string(addrbook_entry_t *const ent, char * str);
typedef struct addrbook_t {
addrbook_entry_t *entries;
size_t entries_len;
size_t entries_cap;
} addrbook_t;
int addrbook_init(addrbook_t *const ab);
void addrbook_destroy(addrbook_t *const ab);
int addrbook_load(addrbook_t *ab, FILE *in);
int addrbook_store(addrbook_t *ab, FILE *out);
void addrbook_destroy(addrbook_t *const ab);
int addrbook_add(addrbook_t *const ab, const addrbook_entry_t *const ent);
addrbook_entry_t *addrbook_get(const addrbook_t *const ab, const char pkey[CRYPT_PKEY_HEXLEN]);