From 05e8fefafc10496c53610668e88591fd2e000769 Mon Sep 17 00:00:00 2001 From: "DLABAL, Eduard" Date: Thu, 15 May 2025 23:24:11 +0200 Subject: [PATCH] Refactor searchUUIDByName: simplify parameter checks, improve memory allocation, and enhance error handling --- src/users.c | 37 ++++++++++++++----------------------- 1 file changed, 14 insertions(+), 23 deletions(-) diff --git a/src/users.c b/src/users.c index c738187..c792f67 100644 --- a/src/users.c +++ b/src/users.c @@ -58,17 +58,12 @@ node_t *searchPersonByUUID( uint16_t searchUUIDByName( list_t *_list, - const char *_name, - const char *_surname, + char *_name, + char *_surname, uint16_t **_uuids_found) { - if (_list == NULL || _name == NULL || _surname == NULL || _uuids_found == NULL) { - return 0; - } - - uint16_t *uuids = NULL; - size_t sum = 0; - size_t capacity = 0; + int sum = 0; + uint16_t *uuids = malloc(sizeof(uint16_t)); pthread_mutex_lock(&_list->lock); 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 (sum >= capacity) { - capacity = (capacity == 0) ? 1 : capacity * 2; - uint16_t *tmp = realloc(uuids, capacity * sizeof(uint16_t)); - if (tmp == NULL) - { - pthread_mutex_unlock(&_list->lock); - free(uuids); - fprintf(stderr, "Fatal error: insufficient memory for this operation\n"); - *_uuids_found = NULL; - return 0; - } - uuids = tmp; + sum++; + uint16_t *uuids = realloc(uuids, sum * sizeof(uint16_t)); + if (uuids == NULL) + { + pthread_mutex_unlock(&_list->lock); + free(uuids); + puts("Fatal error: free memory is not sufficient for this operation"); + exit(EXIT_FAILURE); } - uuids[sum++] = current->user.uuid; + uuids[sum - 1] = current->user.uuid; } } current = current->next; @@ -100,7 +91,7 @@ uint16_t searchUUIDByName( pthread_mutex_unlock(&_list->lock); *_uuids_found = uuids; - return (uint16_t)sum; + return sum; } int addPersonToList(