Free array pointed to by a pointer within a struct

2019-07-31 10:29发布

问题:

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;
    }

回答1:

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.



回答2:

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