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;
}
You can only call
free
on the pointer returned to you bymalloc
and you can only free the whole block, not individual bytes.You want one (1) call to
free
per call tomalloc
. Here you've only allocated one item with room for two characters. Tofree
it, it's pretty straight-forward. Here is what is called a "Safe" release (or free).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 onemalloc
.