-
push and pop functions?
Im having trouble with this push function.. it says im getting a seg fault and I dont know why..
Code:
typedef struct _stacknode{
void *value;
struct _stacknode *next;
struct _stacknode *prev;
}STACKNODE;
typedef struct _stack{
struct _stacknode *sent;
}STACK;
void push(void *value, void *stack)
{
STACKNODE *new_node = malloc(sizeof(STACKNODE));;
STACKNODE *current = stack;
current->prev->next = new_node;
new_node->prev = current->prev;
current->prev = new_node;
new_node->next = current;
}
My program is:
Code:
main(int argc, char *argv[]) {
void *string_stack = create_stack();
int i;
for (i = 1; i < argc; i++)
push(strdup(argv[i]), string_stack);
}
-
it would be good to know the code of the "create_stack" function, so we dont have to assume anything, which is what i am doing now.
on the very first loop in main, it will push a string to the new stack. in the "push" function it will access "current" (the top of our new stack, which is empty). if the top of the stack is initialized to NULL (which i assume it is!), then it will try to access NULL's->prev->next, which doesnt make sense. You need to check the top of the stack before doing anything with it. If it is NULL, you create a new node (like you do already) and assign it to the stack. Each time you create a new node, make sure both links are set properly, and make sure you check if anything is NULL before working with it.
-
Why is your stack struct so complicated? You can see my stack library as an example. It's not commented but I think you will get it.