Thread: push and pop functions?

  1. #1
    Registered User
    Join Date
    Sep 2008

    push and pop functions?

    Im having trouble with this push function.. it says im getting a seg fault and I dont know why..

    typedef struct _stacknode{
        void *value;
        struct _stacknode *next;
        struct _stacknode *prev;
    typedef struct _stack{
        struct _stacknode *sent;
    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:
    main(int argc, char *argv[]) {
        void *string_stack = create_stack();
        int i;
        for (i = 1; i < argc; i++)
            push(strdup(argv[i]), string_stack);

  2. #2
    Registered User
    Join Date
    Oct 2006
    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.

  3. #3
    Registered User
    Join Date
    Aug 2008
    Belgrade, Serbia
    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.
    Vanity of vanities, saith the Preacher, vanity of vanities; all is vanity.
    What profit hath a man of all his labour which he taketh under the sun?
    All the rivers run into the sea; yet the sea is not full; unto the place from whence the rivers come, thither they return again.
    For in much wisdom is much grief: and he that increaseth knowledge increaseth sorrow.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. swapping pointers
    By csvraju in forum C Programming
    Replies: 17
    Last Post: 04-01-2009, 03:18 AM
  2. Help calling function is asm
    By brietje698 in forum C++ Programming
    Replies: 24
    Last Post: 12-06-2007, 04:48 PM
  3. Inline asm
    By brietje698 in forum C++ Programming
    Replies: 5
    Last Post: 11-11-2007, 02:54 PM
  4. Getting position from game..
    By brietje698 in forum C++ Programming
    Replies: 1
    Last Post: 10-26-2007, 12:15 PM
  5. Queues
    By ramayana in forum C Programming
    Replies: 22
    Last Post: 01-01-2006, 02:08 AM