1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
#include "list.h"
static void _print_int(void* a_n) {
int n = *((int*)a_n);
printf("%d", n);
}
static void _dummy_free_fn(void* a_value) {
}
static void _demo_list_of_ints() {
// Create EMPTY list
Node* head = NULL;
Node* tail = head;
// Populate list
int n1 = 5, n2 = 6, n3 = 7;
append(&n1, &head, &tail);
append(&n2, &head, &tail);
append(&n3, &head, &tail);
print_list(head, _print_int);
free_list(&head, &tail, _dummy_free_fn);
assert(head == NULL && tail == NULL); // List should be empty now.
}
static void _print_string(void* a_value) {
fputs(a_value, stdout);
}
static void _demo_list_of_strings_on_data_segment() {
// Create EMPTY list
Node* head = NULL;
Node* tail = head;
// Populate list
append("sriracha", &head, &tail);
append("barbecue", &head, &tail);
append("ponzu", &head, &tail);
print_list(head, _print_string);
free_list(&head, &tail, _dummy_free_fn);
assert(head == NULL && tail == NULL); // List should be empty now.
}
char* _strdup(char* src) { // Copy a string into a newly allocated buffer on the heap
char* s = malloc(sizeof(*s) * (strlen(src) + 1));
return strcpy(s, src);
}
static void _free_string_on_heap(void* a_value) {
free(a_value);
}
static void _demo_list_of_strings_on_heap() {
// Create EMPTY list
Node* head = NULL;
Node* tail = head;
// Populate list, while copying each string to a newly allocated buffer on the heap.
append(_strdup("sriracha"), &head, &tail);
append(_strdup("barbecue"), &head, &tail);
append(_strdup("mustard"), &head, &tail);
print_list(head, _print_string);
free_list(&head, &tail, _free_string_on_heap);
assert(head == NULL && tail == NULL); // List should be empty now.
}
int main(int argc, char* argv[]) {
_demo_list_of_ints();
_demo_list_of_strings_on_data_segment();
_demo_list_of_strings_on_heap();
return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2021 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.