Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to realloc after memmove when remove an element from dynamic array?

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?

like image 926
M. Fatih Avatar asked Dec 28 '15 10:12

M. Fatih


1 Answers

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.

like image 91
Ctx Avatar answered Oct 04 '22 15:10

Ctx