Files
assm-test/src/list.c
T

66 lines
1.5 KiB
C

#include "../includes/list.h"
List* CreateList() {
List *new = malloc(sizeof(List));
if (!new) {
fprintf(stderr, "Failed to malloc() for new new List.\n");
return NULL;
}
new->content = malloc(sizeof(void*) * LISTDEFAULTSIZE);
if (!new->content) {
fprintf(stderr, "Failed to malloc() memory for List contents.\n");
free(new);
return NULL;
}
new->size = 0;
new->capacity = LISTDEFAULTSIZE;
return new;
}
int AddListItem(const void *value, size_t size, List* list) {
if (!list) return -1;
if (!value) return -1;
if (size == 0) return -1;
if (list->capacity < list->size + 1) {
void* ptr = realloc(list->content, sizeof(void*) * list->capacity * 2);
//Note: realloc will free list->root if it succeeds.
if (!ptr) {
fprintf(stderr, "Failed to resize array with realloc() (%d bytes).\n", list->capacity * 2);
return -1;
}
list->content = ptr;
list->capacity = list->capacity * 2;
}
void* item = calloc(1, size);
if (!item) {
fprintf(stderr, "Failed to calloc() new memory (%lu bytes).\n", size);
return -1;
}
memcpy(item, value, size);
list->content[list->size] = item;
list->size++;
return 0;
}
void DestroyList(List* list) {
if (!list) return;
for(int i = 0; i < list->size; i++) {
free(list->content[i]);
}
free(list->content);
free(list);
}