1

I have a stack implemented in dynamic array. Below are some of my functions. When I call stk_reset function, it seems that the stack is not freed completely.

Here is my struct. It is a requirement that I have to have a pointer inside struct pointing to the dynamic array

    typedef struct stack {
        char *items;
        int arrSize;
        int top;
    } StackStruct;


    void stack_create(StackStruct *s) {
        char *arr = malloc(sizeof(char)*2);

        if (arr == NULL) {
            printf("Insufficient memory to initialize stack.\n");
            return;
        }

        s->arrSize = 2;
        s->items = arr;
        s->top = -1;
    }

How do I deallocate each element of the array holding the stack? I used this statement free((s->items)++) with a for loop, but it did not work.

    void stk_reset(StackStruct *s) {
    int i;

        for (i = 0; i <= s->arrSize; i++)
            free((s->items)++);
        free(s->items);
        s->items = NULL;
        s->top = -1;
        s->arrSize = 0;
    }
2
  • You should learn what malloc and free do, practice using them on a simple example, and then revisit your design. Commented Feb 13, 2014 at 1:23
  • 1
    free() doesn't work that way. Commented Feb 13, 2014 at 1:25

2 Answers 2

1

You can only call free on the pointer returned to you by malloc and you can only free the whole block, not individual bytes.

Sign up to request clarification or add additional context in comments.

Comments

0

You want one (1) call to free per call to malloc. Here you've only allocated one item with room for two characters. To free it, it's pretty straight-forward. Here is what is called a "Safe" release (or free).

if (s->items != NULL) {
    free(s->items);
    s->items = NULL; // Reset to be safe.
}

Though to use this, you will need to make sure you initialize your value to NULL before you try to use it: s->items = NULL;.

No other free calls are required, and certainly not in a loop when you only had one malloc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.