Generic Linked List in C
A simple approach using void pointers

I’m a full-stack developer, writing web application mainly in .Net and Node.js stack. Pretty high-level stuff, but now and then I’m involved with automation, IoT or retro-programming projects where the good old C language reigns in its full glory.
Sometimes, although, I miss some functionalities of higher-level languages, like Generics. Some people out there use the preprocessor to emulate things like TList<T> but, with this approach, the code becomes messy pretty fast so I tend to implement it with void pointers.
The typical approach for linked lists
In a linked list, typically, we have a node structure with a pointer to the next node and a field to hold the data. So, if we want a list of integers, we could write a struct as we did in the listing 01 and then write the functions to manipulate it (add to list, remove from list, search in the list, etc…).
Cool, but and if we also need, for instance, a list of text? We should declare another struct and reimplement all the functions to manipulate the list, duplicating our code for every different data type we use.
So, how to write a reusable list capable of work with any data type?
Using void pointers, of course!
Void pointers to the rescue!
By using void pointers ( void*), we can write an abstract data type, like a linked list, capable of hold and manipulate any data type. And the trick is simple! Look at the listing 02.
Now, we can point anything to the data field of the Node structure with no need to rewrite the functions.
What we did here?
Look at the List structure. It has two interesting fields: an integer data_size to allow allocate room for new items and a function pointer callback_free to allow the list free its nodes. Now we can create generic methods to add and remove items based on the data size instead of their type.
Look at the following code and see how we instantiate a new Node and copy the contents of the data param to the node’s data field using the data_size information.
Now, for removing nodes, we need to free its data.
If the data held on the node is a simple datatype we can just call free on the data field, but… what if the data referenced in the node is a complex structure? Well, in this case, we call a user-defined callback to make the job inside the free_node_data function.
Thats it! Simple and very useful.
Following this idea, we can complete the LinkedList implementation with the methods we need.
Here is a “one file” implementation, but the full source code is available on a Github repository.
Thank you!
