Hyperboreus
Hyperboreus

Reputation: 32439

Correctly freeing pointer to linked list

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:

  1. Are the first lines of makeStack and makeStackItem sensible and necessary?

  2. Is the last line of freeStack sensible and necessary?

  3. Once main returns, have I freed all the memory previously allocated?

  4. How can I see whether I have memory leaks or not?

Thank you very much in advance.

Upvotes: 0

Views: 72

Answers (1)

Charlie Burns
Charlie Burns

Reputation: 7044

Are the first lines of makeStack and makeStackItem sensible and necessary? yes except for the casting malloc issue

Is the last line of freeStack sensible and necessary? yes

Once main returns, have I freed all the memory previously allocated? yes

How can I see whether I have memory leaks or not? use valgrind

I would toss the casts of 0 too.

Upvotes: 1

Related Questions