Code cleanup in the List code. Possibly saved myself some headache in the future by using the right pointer type in the struct definition.
This commit is contained in:
+9
-9
@@ -8,9 +8,9 @@ List* CreateList() {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
new->root = malloc(sizeof(void*) * LISTDEFAULTSIZE);
|
||||
new->content = malloc(sizeof(void*) * LISTDEFAULTSIZE);
|
||||
|
||||
if (!new->root) {
|
||||
if (!new->content) {
|
||||
fprintf(stderr, "Failed to malloc() memory for List contents.\n");
|
||||
free(new);
|
||||
return NULL;
|
||||
@@ -28,27 +28,27 @@ int AddListItem(const void *value, size_t size, List* list) {
|
||||
if (size == 0) return - 1;
|
||||
|
||||
if (list->capacity < list->size + 1) {
|
||||
void* ptr = realloc(list->root, sizeof(void*) * list->capacity * 2);
|
||||
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->root = ptr;
|
||||
list->content = ptr;
|
||||
list->capacity = list->capacity * 2;
|
||||
}
|
||||
|
||||
void* item = malloc(size);
|
||||
void* item = calloc(1, size);
|
||||
|
||||
if (!item) {
|
||||
fprintf(stderr, "Failed to malloc() new memory (%lu bytes).\n", size);
|
||||
fprintf(stderr, "Failed to calloc() new memory (%lu bytes).\n", size);
|
||||
return -1;
|
||||
}
|
||||
|
||||
memcpy(item, value, size);
|
||||
|
||||
list->root[list->size] = item;
|
||||
list->content[list->size] = item;
|
||||
list->size++;
|
||||
|
||||
return 0;
|
||||
@@ -58,9 +58,9 @@ void DestroyList(List* list) {
|
||||
if (!list) return;
|
||||
|
||||
for(int i = 0; i < list->size; i++) {
|
||||
free(list->root[i]);
|
||||
free(list->content[i]);
|
||||
}
|
||||
|
||||
free(list->root);
|
||||
free(list->content);
|
||||
free(list);
|
||||
}
|
||||
Reference in New Issue
Block a user