The fifo_free function only knows how to free up memory used for
fifonode_t
items, it doesn't know what to do with the data (pointed to by fn_data) that is in those items. This is wherefreefn
come in.The parameter
void (*freefn)(void *)
is a pointer to a function. The function takes a void pointer. This is used to free the data that is stored against eachfifonode_t
in your FIFO.In some cases you might not need to do anything about freeing the extra data (say you were storing pointers to some other static data). In that case, you could pass NULL for
freefn
and the function will usefifo_nullfree
as the function, which basically does nothing.Note: the
fifo_free
function could just as easily have done the if test inside the loop and only called thefreefn
function if it wasn't NULL. Possibly they have some reason not to.
Specific C fifo implementation confusion
سؤال
I need to use a FIFO for a project I'm working on. I found this implementation on the internet and I can't figure out what's going on in this function; I'm hoping someone can enlighten me.
/* Free an entire fifo */
void fifo_free(fifo_t *f, void (*freefn)(void *))
{
fifonode_t *fn = f->f_head;
fifonode_t *tmp;
if (freefn == NULL)
freefn = fifo_nullfree;
while (fn) {
(*freefn)(fn->fn_data);
tmp = fn;
fn = fn->fn_next;
free(tmp);
}
free(f);
}
...
/*ARGSUSED*/
static void fifo_nullfree(void *arg)
{
/* this function intentionally left blank */
}
See how it uses
void (*freefn)(void *)
as a parameter? Why? Why is that pointer passed into the function? What's the purpose of(*freefn)(fn->fn_data)
What's the point of these lines?
if (freefn == NULL) freefn = fifo_nullfree;
Wouldn't a comment in this situation be just as effective?
You can see a full copy of this implementation here
المحلول
لا تنتمي إلى StackOverflow