I’m implementing a generic Linked List in C
struct Node
{
void* data;
struct Node* next;
};
Is it better to let the user worry about allocating and deallocating what data will point to, or should we do it ourselves? If left to the user they may store stack objects into the list which could cause problems later. I just wanted to know which design is better.
The general rule of thumb is usually: Who allocates a memory – is responsible for freeing it.
In your case, you should take care for the nodes themselves, and the user should be responsible for the
data.It makes sense because:
data– it could be a complex type that needs freeing in inner fields as well, or it could be pointing to a stack allocated space, which will cause an error if trying to free it.list – it does not mean he wants to destroy the data. Maybe the
list is a queue, and the element is currently being processed by
him?