Elastic array block with malloc realloc
I'm trying to implement a dynamic array using a struct:
Code:
typedef struct
{
size_t count, el_size, alloc_count;
void *data;
} List;
Then I can start off the array using:
Code:
List *List_new(size_t alloc_count, size_t el_size)
{
List *list = malloc(sizeof *list + alloc_count * el_size);
if (list == NULL)
return NULL;
list->count = 0;
list->el_size = el_size;
list->alloc_count = alloc_count;
return list;
}
However when I want to realloc the array, I'm not seeing what I'm doing wrong with this function as it is seg-faulting when copying the next element using memcpy after the realloc has been done:
Code:
bool List_add(List *list, void *data)
{
if (list->count > list->alloc_count - 1)
{
List *swap = (List *) realloc(list, sizeof *list + (list->alloc_count + 256) * list->el_size);
if (swap == NULL)
return 0;
list = swap;
list->alloc_count += 256;
}
memcpy(list + sizeof *list + list->count * list->el_size, data, list->el_size);
list->count++;
return 1;
}