Thread: Stack with linked list, working, but I know I'm doing something dirty!

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Dec 2011
    Posts
    13

    Stack with linked list, working, but I know I'm doing something dirty!

    I finally got it working, but I'm not satisfied because I'm not freeing the memory myself. I'm not really sure what to do and was hoping to get a little advice.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct list{
        char element;
        struct list * node;
    } list;
    
    int push(int data, list **ptr){
        list * tmp;
        tmp = malloc(sizeof(list));
        tmp->node = (*ptr)->node;
        tmp->element = data;
        (*ptr)->node = tmp;
        return 0;
    
    }
    
    int pop(list **ptr){
        if( (*ptr)->node != NULL ){
            int tmp;
            tmp = (*ptr)->node->element;
            free((*ptr)->node); //should be here I found out
            (*ptr)->node = (*ptr)->node->node;
            //free((*ptr)->node); causes junk data?
            return tmp;
        } else {
            fputs("Mismatched pop!\n",stderr);
            exit(1);
        }
    }
        
    int main(){
        list * head;
        head = malloc(sizeof(list));
        
        int i;
        for(i = 0;i<=10;i++)
            push(i,&head);
        for(i = 0;i<=10;i++)
            printf("%d\n",pop(&head));
        return 0;
    }
    Wow, I just figured it out, stupid mistake. Anyways, if anyone could at least check it to see if there are any other dirty tricks I pulled I'd be grateful.
    Last edited by XenoReseller; 04-12-2012 at 04:49 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. stack using linked list problem
    By effa in forum C++ Programming
    Replies: 3
    Last Post: 09-18-2009, 12:10 PM
  2. STACK/FIFO as a linked list
    By BlackOps in forum C Programming
    Replies: 2
    Last Post: 07-24-2009, 02:04 PM
  3. Stack in linked list
    By mag_chan in forum C Programming
    Replies: 2
    Last Post: 11-09-2005, 05:31 AM
  4. Linked list Stack question
    By lyrick in forum C++ Programming
    Replies: 4
    Last Post: 09-23-2005, 06:23 AM
  5. linked list stack question
    By Drew in forum C++ Programming
    Replies: 2
    Last Post: 09-11-2003, 05:05 AM