#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    142
    Rep Power
    2

    Run-time errors with linked lists


    All I'm trying to do is print a value in a linked list.
    What's wrong with this code?

    main.c
    Code:
    #include "list1.h"
    #include <string.h>
    
    int main()
    {
        node_t *n1_p, *n2_p, *n3_p;
        n1_p = (node_t *)malloc(sizeof(node_t));
        strcpy(n1_p->current, "AC");
        n1_p->volts = 115;
    
        n2_p = (node_t *)malloc(sizeof(node_t));
        strcpy(n2_p->current, "DC");
        n2_p->volts = 12;
    
        n2_p = n3_p;
        n1_p->linkp = n2_p;
    
        printf("%d", n2_p->volts);
    }
    list1.h
    Code:
    #ifndef INCL
        #define INCL
    
        #include <stdlib.h>
        #include <stdio.h>
    
        #define PRT_TRUE(statement) \
            printf("%s: %d\n", #statement, statement)
    
        #define PRT_INT(label) \
            printf("%s = %d\n", #label, (label))
    
        typedef struct node_s
        {
            char current[3];
            int volts;
            struct node_s *linkp;
        } node_t;
    
    #endif // INCL
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,626
    Rep Power
    4247
    You have this line:
    Code:
        n2_p = n3_p;
    n3_p is uninitialized and you're losing all the stuff you allocated and set in n2_p before this.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,163
    Rep Power
    2222
    n3_p is an uninitialized pointer.

    Also, with this,
    n2_p = n3_p;
    you are dropping n2_p, which creates a memory leak. Everything you do with pointers must work to avoid memory leaks, just as everything you do with a power saw must work to keep all your extremities attached to your body.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    142
    Rep Power
    2
    Thanks guys.

    I somehow switched the left and right of my assignment statements from what I intended.
    I'll read up on memory leaks.

IMN logo majestic logo threadwatch logo seochat tools logo