Thread: Please Need help with a linked List

  1. #1
    Registered User
    Join Date
    Sep 2015
    Posts
    19

    Please Need help with a linked List

    The code bellow creates structures and links them using pointers,
    prints the structures or quits and frees the allocated memory
    for the structures

    what happens is the following
    i add the first structure... prints fine
    i add the second structure... prints fine
    i add the third... press print and the program crashes


    Code:
    //*FSpointer is the first structure in the list
    void printfunc(typeLS *FSpointer){
        
        typeLS *holder3 = FSpointer;
        
        while(holder3 != NULL){
    
            printf("name:%s float:%f\n",holder3->name,holder3->decimals);
            
            holder3 = holder3->forward;
            if(holder3 != NULL){
                printf("not NULL\n");
            }
        }
        printf("exited loop\n");
    so far i know that the while loop can't stop if i add more than 2
    structures, because for some reason structure 3 forward pointer
    is not NULL even though there is no structure after it.

    I can't grasp where the code logic is wrong, adding a second structure works fine, and adding a 3rd structure uses the same logic as adding the second structure but it doesn't work WTF?




    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    typedef struct LSexample{
        
        char name[52];
        float decimals;
        struct LSexample *forward;
    }typeLS;
    
    typeLS *returnPointerToAllocatedMemory(typeLS *MainPointers){
        char UserInput5[16];
        fgets(UserInput5, 15,stdin);
        typeLS *PointertoAllocatedMemory = malloc(sizeof(typeLS));
    
        sscanf(UserInput5,"%s %f",PointertoAllocatedMemory->name,&PointertoAllocatedMemory->decimals );
    
        printf("Name:%s float:%f\n",PointertoAllocatedMemory->name,PointertoAllocatedMemory->decimals);
        if(MainPointers != NULL){//if there is somethign behind then set
                                    //    whats behind pointer to point at the newly created structure 
            MainPointers->forward = PointertoAllocatedMemory;//mainpointers is the previous structure
                                                            // if there isn't one it will be NULL
        }
        return PointertoAllocatedMemory;
    }
    void cleanUp(typeLS *FirstStructure1){
        
        
        typeLS *freeThisAllocatedMemory = NULL;
        typeLS *HoldPointerForward = NULL;
        freeThisAllocatedMemory = FirstStructure1;
        
        if(freeThisAllocatedMemory != NULL){
            printf("Free name:%s float %f\n",freeThisAllocatedMemory->name,freeThisAllocatedMemory->decimals);
            HoldPointerForward = freeThisAllocatedMemory->forward;
            free(freeThisAllocatedMemory); 
            freeThisAllocatedMemory = HoldPointerForward;
    
        }
    }
    void printfunc(typeLS *FSpointer){
        
        typeLS *holder3 = FSpointer;
        
        while(holder3 != NULL){
    
            printf("name:%s float:%f\n",holder3->name,holder3->decimals);
            
            holder3 = holder3->forward;
            if(holder3 != NULL){
                printf("not NULL\n");
            }
        }
        printf("exited loop\n");
        
    }
    
    
    int main(){
        typeLS *Firststructure = NULL;//this pointer will point at the first structure in the list 
                                        
        typeLS *holderr = NULL; //this pointer will point at structures temporarily
        char UserInput[16];
        char translation[16];
        while(fgets(UserInput, 15,stdin)){
            sscanf(UserInput,"%s",translation);
            if(strncmp(translation, "add",3)==0){
                printf("Ready to add...\n");
                if(Firststructure == NULL){
                    Firststructure = returnPointerToAllocatedMemory(NULL);
                    holderr = Firststructure;
                }else{
                    holderr = returnPointerToAllocatedMemory(holderr);
                }
            }else if(strncmp(translation, "print",5)==0){
                printf("Printing...\n");
                printfunc(Firststructure);
            }else if(strncmp(translation, "quit",4)==0){
                printf("Breaking...\n");
                break;
            }
        }
        cleanUp(Firststructure);
        return 0;
    }

  2. #2
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    That code looks really messy.

    I think this should be a working version of adding a node to a list though :
    Code:
    struct node
    {
        int data;
        struct node *next;
    };
    
    // append node after current one
    void insert( struct node *curr, int data )
    {
        struct node *tmp = new_node( data );
        struct node *old = curr->next;
    
        curr->next = tmp
        tmp->next = old;
    
        return;
    }
    I think that should do it. This code isn't tested but the basic idea is, you take the previous "next" pointer of the current node and then assign it to the new node. The new node's "next" pointer inherits the old value.

  3. #3
    Registered User
    Join Date
    Sep 2015
    Posts
    19
    Thanks mutantjohn but i already know how a singly linked list works
    anyway it turns out there was no problem with any of my code logic
    apart from the cleanUp() function but that's besides the point,
    it turns out that the crash was caused by the name[52]
    when i changed it to 12 the crashing stopped, really weird,
    is there a limit to how big an array should be inside a structure?

  4. #4
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    That sounds super duper odd and like something is very, very wrong.

    This code works perfectly.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    struct node
    {
        char data[ 52 ];
        struct node *next;
    };
    
    
    struct node* new_node( const char *str )
    {
        struct node *tmp = malloc( sizeof( *tmp ) );
    
    
        strcpy( tmp->data, str );
        tmp->next = 0;
    
    
        return tmp;
    }
    
    
    // insert node after current one
    // return pointer to newly created node
    struct node* insert( struct node *curr, const char *str )
    {
        struct node *tmp = new_node( str );
    
    
        struct node *old = curr->next;
    
    
        curr->next = tmp;
        tmp->next = old;
    
    
        return tmp;
    }
    
    
    void free_list( struct node *head )
    {
        while ( head != 0 )
        {
            struct node *old = head;
            head = head->next;
    
    
            free( old );
        }
    }
    
    
    void print_list( struct node *head )
    {
        while ( head != 0 )
        {
            printf( "%s\n", head->data );
    
    
            head = head->next;
        }
    }
    
    
    int main( void )
    {
        struct node *head = new_node( "I" );
    
    
        struct node *tail = insert( head, "love" );
        tail = insert( tail, "myself!" );
        tail = insert( tail, "And" );
        tail = insert( tail, "when" );
        tail = insert( tail, "you" );
        tail = insert( tail, "lookin'" );
        tail = insert( tail, "at" );
        tail = insert( tail, "me," );
        tail = insert( tail, "tell" );
        tail = insert( tail, "me," );
        tail = insert( tail, "what" );
        tail = insert( tail, "do" );
        tail = insert( tail, "you" );
        tail = insert( tail, "see?" );
    
    
        print_list( head );
    
    
        free_list( head );
    
    
        return 0;
    }

  5. #5
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    Moderators: I think i found a bug

    >_<

    You shouldn't start new threads to discuss the same issue.

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

  6. #6
    Registered User
    Join Date
    Sep 2015
    Posts
    19
    how long have you been coding?

  7. #7
    Registered User
    Join Date
    Sep 2015
    Posts
    19
    sorry i just thought if it's a bug maybe i should warn everyone

  8. #8
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    I think the problem might be in your sscanf calls. Or rather, it's in how you're acquiring user input.

  9. #9
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Quote Originally Posted by Anonymouss View Post
    Thanks mutantjohn but i already know how a singly linked list works
    anyway it turns out there was no problem with any of my code logic
    Wrong, there is definitely an error in your code logic. Where, in all of this, do you ever set forward to NULL? Every time you add a node to the end of the list, you must initialize this pointer to NULL, or else how are you going to know when you hit the end of the list? In your current implementation, you only initialize the forward pointer when the next element has been added, which always leaves the last node's forward pointer in an indeterminate state.

    That is, if you have 4 elements in the list, you have three that are properly linked to the next element, and the last element has an uninitialized pointer. Attempting to dereference that pointer is your error.

    The fact it works at all is because sometimes you get lucky.

    You should be doing a
    Code:
    PointertoAllocatedMemory->forward = NULL;
    immediately upon creating that structure.
    Last edited by Cat; 09-03-2015 at 06:22 PM.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  10. #10
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    how long have you been coding?
    O_o

    Well...

    o_O

    I've been coding for about three months.

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

  11. #11
    Registered User
    Join Date
    Sep 2015
    Posts
    19
    i was asking MutantJohn, and dude how you post 5k times in 3 months you must be skipping sleep and eating

  12. #12
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Lol I've been coding for about 2.5 years. Posters like phantom have really helped me out.

  13. #13
    Registered User
    Join Date
    Sep 2015
    Posts
    19
    yeah he is good, and he has good profile picture

  14. #14
    Registered User MutantJohn's Avatar
    Join Date
    Feb 2013
    Posts
    2,665
    Quote Originally Posted by Anonymouss View Post
    yeah he is good, and he has good profile picture
    Not better than mine!

  15. #15
    Registered User
    Join Date
    Sep 2015
    Posts
    19
    You have a nice profile picture too.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 13
    Last Post: 09-22-2013, 10:34 PM
  2. Declaring linked list inside linked list
    By blueboyz in forum C Programming
    Replies: 33
    Last Post: 04-20-2012, 10:13 AM
  3. single linked list to double linked list (help)
    By Countfog in forum C Programming
    Replies: 8
    Last Post: 04-29-2008, 08:04 PM
  4. singly linked list to doubly linked list
    By t48j in forum C Programming
    Replies: 3
    Last Post: 03-23-2005, 06:37 PM
  5. Replies: 6
    Last Post: 03-02-2005, 02:45 AM

Tags for this Thread