After more than 10 years of having the luxury of using garbage collected languages, I am returning to C99 and obviously I am having difficulties with memory management.
I have a linked list consisting of stack items and a type Stack
which points to the address of the first element of this list.
This is my code so far:
#include <stdio.h>
#include <stdlib.h>
typedef struct StackItem
{
int head;
struct StackItem* next;
} StackItem;
typedef StackItem** Stack;
StackItem* makeStackItem (int head)
{
StackItem* a = (StackItem*) malloc (sizeof (StackItem) );
a->head = head;
a->next = (StackItem*) 0;
return a;
}
Stack makeStack ()
{
Stack stack = (Stack) malloc (sizeof (StackItem*) );
*stack = (StackItem*) 0;
return stack;
}
void pushStack (StackItem* item, Stack stack)
{
item->next = *stack;
*stack = item;
}
void freeStack (Stack stack)
{
StackItem* current = *stack;
StackItem* next;
while (current != 0)
{
next = current->next;
free (current);
current = next;
}
free (stack);
}
int main ()
{
Stack stack = makeStack ();
for (int i = 0; i < 10; i++)
pushStack (makeStackItem (i), stack);
printf ("Here be dragons.\n");
freeStack (stack);
return 0;
}
My questions are:
Are the first lines of
makeStack
andmakeStackItem
sensible and necessary?Is the last line of
freeStack
sensible and necessary?Once
main
returns, have I freed all the memory previously allocated?How can I see whether I have memory leaks or not?
Thank you very much in advance.