Thread: Ok, C Board, what am I doing wrong? (Linked lists)

  1. #1
    Third Eye Babkockdood's Avatar
    Join Date
    Apr 2010
    Posts
    352

    Ok, C Board, what am I doing wrong? (Linked lists)

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct node {
    	int value;
    	struct node *next;
    } block;
    
    int main(void) {
    	block *root = NULL;
    	block *c;
    	int x;
    	c = root;
    	for (x = 0; x < 10; x++) {
    		c = (block *)malloc(sizeof(block));
    		c->value = (x*4);
    		// 0, 4, 8, 12, 16, 20, etc
    		c = c->next;
    	}
    	for (c = root; c; c = c->next)
    		printf("%d\n", c->value);
    	return 0;
    }
    The first for loop is supposed to allocate memory for 10 list items, and assign the value inside the list item to a multiple of four.

    The second for loop is supposed to go to the beginning of the list and print each list item.

    This program compiles fine, but it doesn't output anything.
    Last edited by Babkockdood; 03-16-2012 at 02:48 PM.
    Quote Originally Posted by The Jargon File
    Microsoft Windows - A thirty-two bit extension and graphical shell to a sixteen-bit patch to an eight-bit operating system originally coded for a four-bit microprocessor which was written by a two-bit company that can't stand one bit of competition.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Code:
    c = c->next
    You just allocated memory for c, but it's uninitialized. That means c->next contains garbage. You then assign that garbage to c and lose your handle to the memory you just malloc'ed (memory leak). You can't add to the end of the list without either a temp pointer that you use to iterate to the last node, or a tail pointer that you always maintain as pointing to the last node in the list.

    Code:
    for x from 0 to 9
        c = malloc
        c->value = x*4
        c->next = NULL
        if (root == NULL) // empty list
            root = c
        else
            temp = last node in list
            temp->next = c
            update tail pointer if you have one

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Double Linked Dynamic Lists Vs Unrolled Linked Lists
    By lantzvillian in forum C Programming
    Replies: 6
    Last Post: 02-14-2012, 01:07 PM
  2. Replies: 4
    Last Post: 05-01-2010, 10:19 PM
  3. simple linked lists am i doing anything wrong
    By nik2 in forum C Programming
    Replies: 4
    Last Post: 02-17-2010, 10:03 AM
  4. Question about Linked lists of lists
    By hear_no_evil in forum C Programming
    Replies: 2
    Last Post: 11-08-2004, 02:49 AM
  5. question on linked lists(stack with linked lists)
    By dionys in forum C Programming
    Replies: 1
    Last Post: 06-02-2004, 11:08 AM