/*
Compile:
make readme-ex01a-using-int
*/
#include <stdio.h> /* printf() */
#include <stdlib.h> /* calloc() */
typedef struct node_int_t
{
struct node_int_t *next;
int data; /* NOT VERY GENERIC */
} node_int_t;
/* Delete all nodes */
void node_cleanup(node_int_t **head)
{
node_int_t *current = *head, *next = NULL;
while (current)
{
next = current->next;
free(current);
current = next;
}
/* Set variable to NULL *before* free(). */
/* Valgrind doesn't like it the other way around! */
*head = NULL;
free(*head);
}
int
main(int argc, char *argv[])
{
node_int_t *node1 = calloc(1, sizeof(*node1));
node_int_t *node2 = calloc(1, sizeof(*node2));
node_int_t *node3 = calloc(1, sizeof(*node3));
node_int_t *node = calloc(1, sizeof(*node));
int i = 0;
printf("\nREADME EX01a\n");
printf("----------------------------------------\n");
/* Create 3 nodes */
node1->data = 12;
node2->data = 99;
node3->data = 37;
node1->next = node2;
node2->next = node3;
node3->next = NULL;
printf("node1->data=%d\n", node1->data);
printf("node1->next->data=%d\n", node1->next->data);
printf("node1->next->next->data=%d\n", node1->next->next->data);
/* Create another 100 nodes, link first node to node3 */
for (i = 0; i < 100; ++i)
{
if (i == 0) node3->next = node;
node->data = i;
node->next = calloc(1, sizeof(*node));
node = node->next;
}
/* Print node 45 of 103 - should print 42 */
node = node1;
for (i = 0; i < 45; ++i)
{
node = node->next;
}
printf("node->data=%d\n", node->data);
/* Delete all nodes */
node_cleanup(&node1);
printf("\nTIP: MEMLEAK CHECK:\n");
printf("valgrind -v --track-origins=yes --leak-check=full --show-leak-kinds=all %s\n", argv[0]);
(void)argc;
printf("----------------------------------------\n\n");
return 0;
}