Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does free() follow pointers?

I'm sure it doesn't, but maybe there's black magic in it, so here's my question:

If I have a struct like this:

struct mystr {
    char * strp,
    unsigned int foo,
};

and I allocate memory for it and want to release it later. Do I have to do

free(mystr_var->strp);
free(mystr_var);

or is the last line enought, does the free() function follow the pointers and free them two?

like image 602
musicmatze Avatar asked Dec 14 '12 11:12

musicmatze


People also ask

Does Free Get rid of the pointer?

The variable holding the memory address is owned by the process and call to free the memory is actually 'call by value' (the value of the pointer variable is passed), so the free function cannot clear the pointer variable.

What happens when free ()?

free() just declares, to the language implementation or operating system, that the memory is no longer required.

What does free do to a pointer in C?

The function free takes a pointer as parameter and deallocates the memory region pointed to by that pointer. The memory region passed to free must be previously allocated with calloc , malloc or realloc . If the pointer is NULL , no action is taken.

What happens to the pointer after free?

Yes, when you use a free(px); call, it frees the memory that was malloc'd earlier and pointed to by px. The pointer itself, however, will continue to exist and will still have the same address. It will not automatically be changed to NULL or anything else.


1 Answers

No, free doesn't follow pointers, you need both lines.

I usually write a function like:

void freemystr(mystr *mystr_var)
{
    if (mystr_var)
    {
        free(mystr_var->strp);
        mystr_var->strp = NULL;
        free(mystr_var);
    }
}
like image 132
jimhark Avatar answered Oct 30 '22 21:10

jimhark