llwfp

Documentation
Login

Documentation

/*
   Compile:
   make readme-ex01c-using-char-p
 */

#define _BSD_SOURCE /* snprintf() */

#include <string.h> /* strlen() */
#include <stdio.h>  /* printf() */
#include <stdlib.h> /* calloc() */

typedef struct node_char_p_t
{
  struct node_char_p_t *next;
  char *data; /* NOT VERY GENERIC */
} node_char_p_t;

/* Delete data for all but the 3 first nodes, as they contain static data, and should not be free():ed */
void data_cleanup(node_char_p_t **node)
{
  node_char_p_t *current = *node;
  while (current)
  {
    free(current->data);
    current = current->next;
  }
}

/* Delete all nodes */
void node_cleanup(node_char_p_t **head)
{
  node_char_p_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_char_p_t *node1 = malloc(sizeof(*node1));
  node_char_p_t *node2 = malloc(sizeof(*node2));
  node_char_p_t *node3 = malloc(sizeof(*node3));
  node_char_p_t *node = malloc(sizeof(*node));
  int i = 0;

  printf("\nREADME EX01c\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='%s'\n", node1->data);
  printf("node1->next->data='%s'\n", node1->next->data);
  printf("node1->next->next->data='%s'\n", node1->next->next->data);

  /* Create another 100 nodes, link first node to node3 */
  for (i = 0; i < 100; ++i)
  {
#define BUFSIZE 16
    char buf[BUFSIZE];
    if (i == 0) node3->next = node;
    snprintf(buf, BUFSIZE, "%d", i);
    node->data = calloc(1, strlen(buf)+1);
    memcpy(node->data, buf, strlen(buf)+1);
    node->next = calloc(1, sizeof(*node));
    node = node->next;
    node->next = NULL;
  }

  /* Print node 45 of 103 - should print "42" */
  node = node1;
  for (i = 0; i < 45; ++i)
  {
    node = node->next;
  }
  printf("node->data='%s'\n", node->data);

  /* Cleanup dynamic data, skipping 3 first nodes */
  data_cleanup(&node3->next);

  /* 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;
}