C Generic Linked List: wrong output

125 views Asked by At

I managed to create a singly linked list for integers. Now I wanted to expand this to all types of data by using a void pointer. Somehow this doesn't work. Could you please take a look at it? Thank you!

not generic: linkedlist.h

// Singly Linked List
#ifndef linked_list     
#define linked_list

#include <stdlib.h>
typedef struct link_list_node {
  struct link_list_node *next;      
  int data;                         
} ll_node;

typedef struct link_list {
  struct link_list_node *head;
} ll;

ll *ll_create(ll_node *head);       
ll_node *ll_node_create(int data);  
ll *ll_insert_end(ll *list, ll_node *node);             
#endif

linkedlist.h

#include "linkedlist.h"
ll *ll_create(ll_node *head){ 
  ll *list = malloc(sizeof(ll));
  list->head = head;
  return list;
}

ll_node *ll_node_create(int data){
  ll_node *node = malloc(sizeof(ll_node));
  node->next = NULL; 
  node->data = data;
  return node;
}

ll *ll_insert_end(ll *list, ll_node *node){
  ll_node *next;
  if (list->head->next == NULL){
    list->head->next = node;
  }
  else{
    for (next = list->head->next; next != NULL; next = next->next){
      if (next->next == NULL){
        next->next = node;
        break;
      }
    }
  }
  return list;
}

linkedlist_main.c:

// gcc -std=c99 -o list linkedlist_main.c linkedlist.c
// Singly Linked List Test

#include "linkedlist.h"
#include <stdio.h>

int main(){

  ll *list = ll_create(ll_node_create(1));
  list = ll_insert_end(list, ll_node_create(2));

  printf("Node 1: %d \n", list->head->data);
  printf("Node 2: %d \n", list->head->next->data);
}

modified was: .h

typedef struct link_list_node {
  struct link_list_node *next;  
  void *data;                       
} ll_node;

.c

ll_node *ll_node_create(void *new_data){
  ll_node *node = (ll_node*)malloc(sizeof(ll_node));
  node->next = NULL; 
  node->data = new_data;
  return node;
}

main

  int dat1 = 1;
  int dat2 = 2;
  ll *list = ll_create(ll_node_create(&dat1));
  list = ll_insert_end(list, ll_node_create(&dat2));
  printf("Node 1: %d \n", list->head->data);
  printf("Node 2: %d \n", list->head->next->data);

There are no compiler errors or warnings: The output is Node 1: strange square with numbers

1

There are 1 answers

0
Beirdo On BEST ANSWER

You will need to change your output line from a %d to a %p to display the pointer itself, or cast the void * to an int * and then dereference it.

Also, be aware that storing pointers to objects on the stack is generally a bad idea as once the objects go out of scope, the pointers will still exist, but be pointing to random crap on the stack. It will cause no end of pain later.