Question

I am trying to free the elements of a struct, which has size_t variables and char. How do free the size_t ones, because I keep getting warnings like

[Warning] passing arg 1 of `free' makes pointer from integer without a cast

Now I understand that i need to make a cast, but I don't know how! Here's the code:

typedef struct collection
{
    char **c;
    size_t nc, na, ne;
} TCS, * ACS;

void Destroy(ACS *x)
{
    int i;
    free((*x)->na);
    for(i=0;i<(*x)->nc;i++)
        free((*x)->c[i]);
    free((*x)->c);
    free((*x)->nc);
    free((*x)->ne);

}

/* allocating */
ACS AlocCS(size_t d, size_t e)
{
    ACS *af=(ACS*)malloc(d);
    if(af==NULL)
        return 0;
    (*af)->na=e;
    (*af)->nc=d;
    (*af)->c=(char**)calloc(e*d,sizeof(char));
    if((*af)->c==NULL){
        free(af);
        return 0;}            

    return *af;
}

I am getting 3 warnings, all related to na,ne,nc. What am I skipping? Thanks!

LE: thanks everyone, my project works now ! Happy holidays!

Was it helpful?

Solution

I am getting 3 warnings, all related to na,ne,nc. What am I skipping?

malloc returns a pointer to a dynamic allocated memory area. size_t variables can't hold such addresses.

You just need to free what you alloced, ie (*af)->c and af.

OTHER TIPS

If you haven't dynamically allocated the variables:

size_t nc, na, ne;

there's no reason why freeing them.

You do not call free on statically allocated variables, only on addresses stored in pointers, which points to the areas formerly allocated.

When you do this:

(*af)->na=e; 
(*af)->nc=d; 

You are not allocating the variables na and nc; you're simply assigning values to these variables that belong to the structure formerly allocated, and pointed by the address stored in af.

You should only call free on objects that were allocated by a call to malloc, realloc, calloc etc. Since these three fields were not created that way you should not attempt to free them.

The memory for these three fields is part of the struct it is allocated when you allocate the struct. It was not separately allocated. And consequently does not need separate deallocation.

The size_t's are local variables, meaning they aren't dynamically allocated (i.e. they are part of the memory allocated for the struct and you don't have to manage their memory manually). Once you free the struct, the local variables will automatically be cleaned up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top