In the stack_enqueue
function you have these two lines:
node_t *n = (node_t*)malloc(sizeof(node_t));
s->head[s->count++] = *n;
The first line dynamically allocates memory. The second line copies from where n
is pointing. Then you simply discard the pointer n
and the memory it points to. This is indeed a memory leak.
The simple solution is to add:
free(n);
after the assignment.
There's a slight problem with this and your whole "list" implementation though, because what you have isn't really a list, but a simple array of structure objects. You could replace relevant lines of stack_enqueue
with e.g.:
s->head[s->count++].data = item;
and then not bother with the list part at all (essentially remove the next
member of the structure, together with all "list" handling).
I think you misunderstand the purpose of the exercise. If s->head
is a pointer, it should not be treated as an array but a pointer to the first node of the list.
So you would have something like
+---------+ +------------+ +-------------+ +-----------+
| s->head | -> | first node | -> | second node | -> ... -> | last node | --> NULL
+---------+ +------------+ +-------------+ +-----------+
That is, s->head
points to the first node. The first nodes next
pointer points to the second node, etc.
You don't have linking of nodes like this at all in your current code.
If you have trouble with understanding linked lists, your text-books should have information about it, and your class should have brought it up as well. And there must be millions of resources available all over the greater Internet about how to implement hand handle lists.