Refactor searchUUIDByName: simplify parameter checks, improve memory allocation, and enhance error handling

This commit is contained in:
2025-05-15 23:24:11 +02:00
parent 7bc938aa69
commit 05e8fefafc
+14 -23
View File
@@ -58,17 +58,12 @@ node_t *searchPersonByUUID(
uint16_t searchUUIDByName( uint16_t searchUUIDByName(
list_t *_list, list_t *_list,
const char *_name, char *_name,
const char *_surname, char *_surname,
uint16_t **_uuids_found) uint16_t **_uuids_found)
{ {
if (_list == NULL || _name == NULL || _surname == NULL || _uuids_found == NULL) { int sum = 0;
return 0; uint16_t *uuids = malloc(sizeof(uint16_t));
}
uint16_t *uuids = NULL;
size_t sum = 0;
size_t capacity = 0;
pthread_mutex_lock(&_list->lock); pthread_mutex_lock(&_list->lock);
node_t *current = _list->head; node_t *current = _list->head;
@@ -79,20 +74,16 @@ uint16_t searchUUIDByName(
{ {
if (strcmp(_name, current->user.name) == 0 && strcmp(_surname, current->user.surname) == 0) if (strcmp(_name, current->user.name) == 0 && strcmp(_surname, current->user.surname) == 0)
{ {
if (sum >= capacity) { sum++;
capacity = (capacity == 0) ? 1 : capacity * 2; uint16_t *uuids = realloc(uuids, sum * sizeof(uint16_t));
uint16_t *tmp = realloc(uuids, capacity * sizeof(uint16_t)); if (uuids == NULL)
if (tmp == NULL) {
{ pthread_mutex_unlock(&_list->lock);
pthread_mutex_unlock(&_list->lock); free(uuids);
free(uuids); puts("Fatal error: free memory is not sufficient for this operation");
fprintf(stderr, "Fatal error: insufficient memory for this operation\n"); exit(EXIT_FAILURE);
*_uuids_found = NULL;
return 0;
}
uuids = tmp;
} }
uuids[sum++] = current->user.uuid; uuids[sum - 1] = current->user.uuid;
} }
} }
current = current->next; current = current->next;
@@ -100,7 +91,7 @@ uint16_t searchUUIDByName(
pthread_mutex_unlock(&_list->lock); pthread_mutex_unlock(&_list->lock);
*_uuids_found = uuids; *_uuids_found = uuids;
return (uint16_t)sum; return sum;
} }
int addPersonToList( int addPersonToList(