Made the List generic, though more care needs to be taken when using it since memory leaks can happen when structs are used with it.

This commit is contained in:
2022-01-17 17:21:40 +00:00
parent 2c18b593ab
commit 929f2a7f4b
3 changed files with 58 additions and 48 deletions
+9 -22
View File
@@ -1,5 +1,4 @@
#include "../includes/list.h"
#include <stdio.h>
List* CreateList() {
List *new = malloc(sizeof(List));
@@ -9,7 +8,7 @@ List* CreateList() {
return NULL;
}
new->root = malloc(sizeof(char*) * LISTDEFAULTSIZE);
new->root = malloc(sizeof(void*) * LISTDEFAULTSIZE);
if (!new->root) {
fprintf(stderr, "Failed to malloc() memory for List contents.\n");
@@ -23,14 +22,16 @@ List* CreateList() {
return new;
}
int AddListItem(const char *value, List* list) {
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->root, sizeof(char*) * list->capacity * 2);
void* ptr = realloc(list->root, sizeof(void*) * list->capacity * 2);
//Note: realloc will free list->root if it succeeds.
if (!ptr) {
fprintf(stderr, "Failed to resize array with realloc() for new item '%s'.\n", value);
fprintf(stderr, "Failed to resize array with realloc() (%d bytes).\n", list->capacity * 2);
return -1;
}
@@ -38,16 +39,14 @@ int AddListItem(const char *value, List* list) {
list->capacity = list->capacity * 2;
}
unsigned long valueLength = strlen(value) + 1; //Plus one for the null byte.
char* item = malloc(valueLength);
void* item = malloc(size);
if (!item) {
fprintf(stderr, "Failed to malloc() new memory for '%s' (length: %lu bytes).\n", value, valueLength);
fprintf(stderr, "Failed to malloc() new memory (%lu bytes).\n", size);
return -1;
}
strncpy(item, value, valueLength);
memcpy(item, value, size);
list->root[list->size] = item;
list->size++;
@@ -55,18 +54,6 @@ int AddListItem(const char *value, List* list) {
return 0;
}
void PrintList(const List* list) {
if (!list) return;
const List *current = list;
printf("Size: %d; Capacity: %d\n", list->size, list->capacity);
for(int i = 0; i < list->size; i++) {
printf("%d: %s\n", i, list->root[i]);
}
}
void DestroyList(List* list) {
if (!list) return;