phreak Posted August 24, 2012 Report Posted August 24, 2012 #ifndef GSLLIST_H#define GSLLIST_H#include <string.h>#include <stdlib.h>#define false 0#define true 1struct sllist_node_t { void * value; struct sllist_node_t * next;};typedef struct sllist_node_t * pnode;typedef struct { pnode first; pnode last; int type_size;} sllist;void init_sllist(sllist * list, int type_size){ list->first = NULL; list->last = NULL; list->type_size = type_size;}void push_back(sllist * list, void * val){ if(list->first == NULL) { list->first = malloc(sizeof(struct sllist_node_t)); list->first->value = malloc(list->type_size); memcpy(list->first->value, val, list->type_size); list->first->next = NULL; list->last = list->first; } else { list->last->next = malloc(sizeof(struct sllist_node_t)); list->last = list->last->next; list->last->next = NULL; list->last->value = malloc(list->type_size); memcpy(list->last->value, val, list->type_size); }}void free_list(sllist * list){ pnode iter = list->first; pnode prev = iter; while(iter->next != NULL) { iter = iter->next; free(prev->value); free(prev); prev = iter; } free(iter->value); free(iter);}int iterate(sllist * list, pnode * iter, void * value){ if((*iter) == NULL) return false; memcpy(value, (*iter)->value, list->type_size); (*iter) = (*iter)->next; return true;}#endifheader : C code - 28 lines - codepadsource : C code - 57 lines - codepadusage :#include <stdio.h>#include "generic_sllist.h"int main(){ sllist list; init_sllist(&list, sizeof(int)); int value = 1; push_back(&list, &value); value = 2; push_back(&list, &value); value = 3; push_back(&list, &value); int vals[] = {4,5,6}; for(int i = 0; i < 3; i++) push_back(&list, &vals[i]); pnode iter = list.first; while(iterate(&list, &iter, &value)) printf("%d\n", value); free_list(&list); return 0;}test : debian-devel ll # gcc -g -std=gnu99 llmain.c generic_sllist.c && ./a.out123456debian-devel ll # valgrind ./a.out==1916== Memcheck, a memory error detector==1916== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.==1916== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info==1916== Command: ./a.out==1916==123456==1916====1916== HEAP SUMMARY:==1916== in use at exit: 0 bytes in 0 blocks==1916== total heap usage: 12 allocs, 12 frees, 120 bytes allocated==1916====1916== All heap blocks were freed -- no leaks are possible==1916====1916== For counts of detected and suppressed errors, rerun with: -v==1916== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)debian-devel ll # Quote