llwfp

Documentation
Login

Documentation

/*
   Compile:
   make readme-ex01b-using-array-of-char
 */

#define _BSD_SOURCE /* snprintf() */

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

#define MAXSIZE 256

typedef struct node_char_arr_t
{
  struct node_char_arr_t *next;
  char data[MAXSIZE]; /* NOT VERY GENERIC */
} node_char_arr_t;

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

  printf("\nREADME EX01b\n");
  printf("----------------------------------------\n");

  /* Create 3 nodes */
  strncpy(node1->data, "12", MAXSIZE);
  strncpy(node2->data, "99", MAXSIZE);
  strncpy(node3->data, "37", MAXSIZE);

  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)
  {
    if (i == 0) node3->next = node;
    snprintf(node->data, MAXSIZE, "%d", i);
    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);

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