diff --git a/cv4/list_ops.c b/cv4/list_ops.c index cffcc27..aa12711 100644 --- a/cv4/list_ops.c +++ b/cv4/list_ops.c @@ -38,11 +38,6 @@ list_t *filter_list(list_t *list, bool (*filter)(list_element_t)) { return NULL; } - list_t *filteredList = (list_t *)malloc(sizeof(list_t)); - if (filteredList == NULL) { - return NULL; - } - size_t count = 0; for (size_t i = 0; i < list->length; ++i) { if (filter(list->elements[i])) { @@ -50,16 +45,14 @@ list_t *filter_list(list_t *list, bool (*filter)(list_element_t)) { } } - filteredList->length = count; - - filteredList->elements = (list_element_t *)malloc(count * sizeof(list_element_t)); - if (filteredList->elements == NULL) { - free(filteredList); + list_t *filteredList = (list_t *)malloc(sizeof(list_t) + count * sizeof(list_element_t)); + if (filteredList == NULL) { return NULL; } - size_t filteredIndex = 0; - for (size_t i = 0; i < list->length; ++i) { + filteredList->length = count; + + for (size_t i = 0, filteredIndex = 0; i < list->length; ++i) { if (filter(list->elements[i])) { filteredList->elements[filteredIndex++] = list->elements[i]; } @@ -87,12 +80,6 @@ list_t *map_list(list_t *list, list_element_t (*map)(list_element_t)) { mappedList->length = list->length; - mappedList->elements = (list_element_t *)malloc(list->length * sizeof(list_element_t)); - if (mappedList->elements == NULL) { - free(mappedList); - return NULL; - } - for (size_t i = 0; i < list->length; ++i) { mappedList->elements[i] = map(list->elements[i]); } @@ -140,12 +127,6 @@ list_t *reverse_list(list_t *list) { reversedList->length = list->length; - reversedList->elements = (list_element_t *)malloc(list->length * sizeof(list_element_t)); - if (reversedList->elements == NULL) { - free(reversedList); - return NULL; - } - for (size_t i = 0; i < list->length; ++i) { reversedList->elements[i] = list->elements[list->length - i - 1]; } @@ -155,7 +136,6 @@ list_t *reverse_list(list_t *list) { void delete_list(list_t *list) { if (list != NULL) { - free(list->elements); free(list); } }