I'm working on a ArrayList implementation in C. ArrayList stores pointers (void*), that means ArrayList is a dynamic array of pointers. Here how I remove an element from ArrayList:
typedef struct
{
void* ptr; // pointer of array (beginning)
int length; // pointer count
}ArrayList;
void ArrayList_Remove(ArrayList *list, int index)
{
memmove(
list->ptr + (sizeof(void*) * index),
list->ptr + (sizeof(void*) * (index + 1)),
(list->length - index) * sizeof(void*)
);
list->length--;
// Do I need to realloc list->ptr to free space?
// list->ptr = realloc(list->ptr, list->length * sizeof(void*));
}
As I commented in code, do I need to realloc list->ptr
or memmove
will do it?
First thing: memmove is not involved in memory allocation at all. It just does what it should, move (potentially overlapping) parts of the memory.
In your example it is not absolutely necessary to realloc the array. It mainly depends if so much elements are removed that there would be a relevant amount of free space for reusage. If you feel that this is indeed relevant, your realloc-statement below looks correct. But keep in mind, that the unallocated space might not be usable at all if just a few elements are deleted per array due to heap fragmentation issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With