Search code examples
cpointersdynamic-memory-allocationfree

How to free a part of contiguous allocated memory in c?


I am new to C. I have a program that allocates some memory using calloc() that store pointers. Those pointers point to places in memory where I store data of people. one pointer for each person. So when I need to delete the data, I free() the pointer to these data. But the memory with the pointers still has that one. I want to free that place too. As I know, I can't say free(ptr+5) for example. How can I do that?


Solution

  • You can't free the start or middle of an allocated block and leave the end of the allocated block alone; so (for deleting an entry in an array):

    • move everything after the entry you're removing up to the end of the allocated block towards the start of the allocated block; so that the piece to be removed is at the end

    • use realloc() to reduce the size of the allocated block (to free the piece at the end).

    Dodgy example (assuming that i is the entry you want to free):

        memmove(&myArray[i], &myArray[i+1], (total_entries - 1 - i) * sizeof(myArray[0]) );
        temp = realloc(myArray, total_entries - 1 * sizeof(myArray[0]));
        if(temp == NULL) {
            /* Ooops. Need to handle the error somehow */
        } else {
            myArray = temp;
            total_entries--;
        }