Added some error handling in the List functions. Just trying to get a feel for how to handle memory allocation failures in C.
This commit is contained in:
+21
@@ -1,8 +1,22 @@
|
||||
#include "../includes/list.h"
|
||||
#include <stdio.h>
|
||||
|
||||
List* CreateList() {
|
||||
List *new = malloc(sizeof(List));
|
||||
|
||||
if (!new) {
|
||||
fprintf(stderr, "Failed to malloc() for new new List.\n");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
new->root = malloc(sizeof(char*) * LISTDEFAULTSIZE);
|
||||
|
||||
if (!new->root) {
|
||||
fprintf(stderr, "Failed to malloc() memory for List contents.\n");
|
||||
free(new);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
new->size = 0;
|
||||
new->capacity = LISTDEFAULTSIZE;
|
||||
|
||||
@@ -16,6 +30,7 @@ int AddListItem(const char *value, List* list) {
|
||||
void* ptr = realloc(list->root, sizeof(char*) * 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);
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -26,6 +41,12 @@ int AddListItem(const char *value, List* list) {
|
||||
unsigned long valueLength = strlen(value) + 1; //Plus one for the null byte.
|
||||
|
||||
char* item = malloc(valueLength);
|
||||
|
||||
if (!item) {
|
||||
fprintf(stderr, "Failed to malloc() new memory for '%s' (length: %lu bytes).\n", value, valueLength);
|
||||
return -1;;
|
||||
}
|
||||
|
||||
strncpy(item, value, valueLength);
|
||||
|
||||
list->root[list->size] = item;
|
||||
|
||||
Reference in New Issue
Block a user