Hello. As part of my program, I have implemented a stack (LIFO) structure, which stores void pointers as its data (seeing as it's intented to store pointers to any type of variable). Here is it's deceleration:
Code:
typedef struct
{
void** data;
unsigned int size;
} stack;
Another part of my program stores these stacks which will contain 'symbols' (a struct) inside another one of these stacks (a super-stack if you will).
A function called 'enter_scope' creates one of these stacks and pushes it into the super-stack:
Code:
int enter_scope(stack* sym_stack)
{
stk_push(sym_stack, stk_create());
if(errno != 0) return 0;
return 1;
}
Another function called 'exit_scope' means to delete all the symbol structs held in top stack of the super stack, then delete that top stack. However, I cannot seem to implement this without causing memory leaks. Here is what I have so far:
Code:
int exit_scope(stack* sym_stack)
{
stack** top_scope = stk_top(sym_stack);
while((*top_scope)->size)
{
symbol* top_symbol = stk_top(*top_scope);
free(top_symbol->data);
free(top_symbol);
stk_pop(*top_scope);
}
free(*top_scope);
stk_pop(sym_stack);
if(errno != 0) return 0;
return 1;
}
If you want to know the output of Valgrind when I run this as my main function:
Code:
int main()
{
stack* symstk = stk_create();
enter_scope(symstk);
exit_scope(symstk);
symstk_destroy(symstk);
return 1;
}
You can find it here: Valgrind output - Pastebin.com.
You may also want to know the contents of stk_top, stk_push and stk_pop.
stk_top:
Code:
void* stk_top(stack* stk)
{
if(stk->size == 0)
{
errno = E_STKTOPEMPTY;
return NULL;
}
return stk->data + (stk->size - 1);
}
stk_push:
Code:
int stk_push(stack* stk, void* new_item)
{
if((stk->data = realloc(stk->data, sizeof(void*) * ++ stk->size)) == NULL)
{
errno = E_STKREALLOC;
return 0;
}
memmove(stk->data + (stk->size - 1), new_item, sizeof(void*));
return 1;
}
stk_pop:
Code:
int stk_pop(stack* stk)
{
if(stk->size == 0)
{
errno = E_STKPOPEMPTY;
return 0;
}
if(((stk->data = realloc(stk->data, sizeof(void*) * -- stk->size)) == NULL) && (stk->size != 0))
{
errno = E_STKREALLOC;
return 0;
}
return 1;
}
Any and all help will be much appreciated.