1

I am doing a C exercise where we are given prototypes, and we have to turn them into functions. I stumbled onto the following prototype:

void ft_lstdelone(t_list *lst, void (*del)(void*))

This function is supposed to delete a node from a linked list, but I don't understand what is happening in the second argument "void (*del)(void*)".

The description of the exercise has:

  1. Parameters -
  • #1 The element to free.
  • #2 The address of the function used to delete the content.
  1. Description - Takes as a parameter an element and frees the memory of the element’s content using the function ’del’ given as a parameter and free the element. The memory of ’next’ must not be freed.

I take from this that I have to use a function as an argument, but it doesn't make any sense.

Can someone help me unwrap what this means?

Yasin Br
  • 1,675
  • 1
  • 6
  • 16
Miguel M
  • 302
  • 3
  • 16
  • 7
    It's a [function pointer](https://stackoverflow.com/questions/840501/how-do-function-pointers-in-c-work). (sorry, changed the link, used the wrong one) – sj95126 Oct 23 '21 at 22:25
  • 1
    https://cdecl.org/ (or the program of the same name) is very handy for helping work out C type signatures. – Shawn Oct 23 '21 at 22:42
  • 1
    Have a look at https://en.wikipedia.org/wiki/Callback_(computer_programming) and/or https://en.wikipedia.org/wiki/Function_pointer, maybe it makes (more) sense afterwards? – Erdal Küçük Oct 23 '21 at 22:44

1 Answers1

1

It actually makes a lot of sense. It is a function pointer, that is, ft_lstdelone will find the location of the element. If it was the first element, then the new first element will be its next. If it was the last element, then its previous will point to null. Otherwise its previous will point to its next.

However, how will you remove the actual item? Will you call free? It seems to be a logical approach first, but if you think it through, you will realize that it's a naive approach. If your list contains elements of composite types, then calling free on it will free the address of your data, but the inner members of your data will still hold some allocated data. This raises the possible issue of memory leak, so, depending on the data type you have at your item, you will have to free it in different manners. This is only known at the time when you call ft_lsdelone, because at that point you know the data type of your data.

So, in order to be able to cope with the different scenarios, the function separates the concerns. This function is only concerned in the manner of how an item is to be removed from a list, but will not worry about its deallocation. Instead, it trusts its caller with the deallocation and expects to get a function that is assumed to handle the deallocation properly.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175