cpointersmemoryfreevoid

How to free memory when casting from a void pointer in C


Question: if I have a pointer to "ints" struct as seen below and I cast it to void and back does that mean I'm not allowed to free it anymore? How does free keep track of the allocation sizes?

typedef struct ints
{
    int size;              
    int *data;       
}
ints;

static void dev_array_cleanup(void *array, array_type type)
{
    switch(type)
    {
        case INT: 
        ints *i = (ints*) array; 
        free(i->data);
        free(i); 
        i = NULL; 
        break;
    }
}

static void* dev_array_set(void *array, int size, array_type type)
{
    void *p;

    switch(type) 
    {
        case INT: 
            ints *i = (ints*) malloc(sizeof(ints));
            i->size = size; 
            i->data = (int*) malloc(size * sizeof(int)); 
            p = (void*) i;
            break;
    }

    return p;
}

Solution

  • I'm not allowed to free it anymore?

    Yes you are allowed to free it. In fact you must (eventually) free it in order to avoid a memory leak.

    free does not care about the type the pointer points to - it accepts a void*.
    And any object pointer can be converted to void*.
    Therefore you can simply call free on the pointer (casted or not).

    How does free keep track of the allocation sizes?

    This is done internally by the runtime library (based on the address of the block) and does not depend on the type.

    A side note:
    You should not cast the result of malloc - see here: Should I cast the result of malloc (in C)?.