#include #include #include #include #include /* Singly linked list with a pointer to the next element and a pointer to a value. */ struct _list { struct _list *next; void *val; }; typedef struct _list list; void *mem_get( size_t size ) { /* Allocate a given chunk of memory to a pointer that is returned. */ void *pt; assert( size > 0 ); if ( ( pt = malloc( size ) ) == NULL ) { fprintf( stderr, "ERROR: Could not allocate %zu byte(s): %s\n", size, strerror( errno ) ); abort(); } return pt; } void mem_free( void *pt ) { /* Free memory from a given pointer. */ void **ppt = ( void ** ) pt; void *p = *ppt; if ( p != NULL ) { free( p ); p = NULL; } *ppt = NULL; } void list_add( list **list_ppt, void *val ) { /* Add a new singly linked list element with a pointer. */ list *list_pt = *list_ppt; list *new = NULL; new = mem_get( sizeof( list ) ); new->val = val; new->next = list_pt; *list_ppt = new; } int main() { int i = 0; list *new = NULL; list *next = NULL; list *elem = NULL; // This test works nicely // char *test = NULL; // // test = mem_get( 100000000 ); // // mem_free( &test ); // // while( 1 ) // ; fprintf( stderr, "Adding ...\n" ); for ( i = 0; i < 10000000; i++ ) { list_add( &new, "TEST" ); } fprintf( stderr, "Freeing ...\n" ); next = new; while ( next != NULL ) { elem = next; next = elem->next; mem_free( &elem ); } fprintf( stderr, "Done\n" ); while( 1 ) ; return EXIT_SUCCESS; }