October 27, 2024
Chicago 12, Melborne City, USA
C#

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;
}



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video