#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void *assert_malloc(size_t size)
{
void *result = malloc(size);
assert(result);
return result;
}
void *assert_calloc(size_t size, size_t type_size)
{
void *result = calloc(size, type_size);
assert(result);
return result;
}
struct PtrList{
void **pointer;
size_t size;
};
PtrList ptr_list_init(size_t size)
{
PtrList result = {(void **)assert_calloc(size, sizeof(void *)), size};
return result;
}
#define ptr_list_add(list_to, type, size) \
((type *)ptr_list_add_(list_to, sizeof(type), size))
void *ptr_list_add_(PtrList *list_to, size_t type_size, size_t size)
{
assert(list_to->pointer);
void *result = assert_malloc(size * type_size);
for(int i = 0; i < list_to->size; ++i)
{
if(list_to->pointer[i] == 0)
{
list_to->pointer[i] = result;
goto FOUND_OPEN_SPOT_LABEL;
}
}
assert(0); // No more space on PtrList.
FOUND_OPEN_SPOT_LABEL:;
return result;
}
void ptr_list_free(PtrList *list_to)
{
assert(list_to->pointer);
for(int i = 0; i < list_to->size; ++i)
{
if(list_to->pointer[i] != 0)
{
free(list_to->pointer[i]);
list_to->pointer[i] = 0;
}
}
list_to->size = 0;
free(list_to->pointer);
list_to->pointer = 0;
}
int main() {
// Init PtrList with 3 null pointers
PtrList some_list = ptr_list_init(3);
// malloc and Add pointer to "PtrList some_list"
int *b = ptr_list_add(&some_list, int, 13);
int *c = ptr_list_add(&some_list, int, 13);
// Same pointers
printf("%i\n", b == some_list.pointer[0]);
printf("%i\n", c == some_list.pointer[1]);
// Wrong
printf("%i\n", c == some_list.pointer[0]);
// Free all
ptr_list_free(&some_list);
return 0;
}