8.1 Program Example

Example 8-1 shows the use of the malloc, calloc, and free functions.

Example 8-1 Allocating and Deallocating Memory for Structures

/*  This example takes lines of input from the terminal until   *
 *  it encounters a Ctrl/Z, it places the strings into an       *
 *  allocated buffer, copies the strings to memory allocated    *
 *  for structures, prints the lines back to the screen, and    *
 *  then deallocates all memory used for the structures.        */

#include  <stdlib.h>
#include  <stdio.h>
#define   MAX_LINE_LENGTH  80

struct line_rec                    /*  Declare the structure.   */
   {
      struct line_rec *next;       /*  Pointer to next line.    */
      char   *data;                /*  A line from terminal.    */
   };

int main (void)
{
   char   *buffer;
                                   /* Define pointers to        *
                                    *  structure (input lines). */

   struct line_rec  *first_line = NULL, *next_line, *last_line = NULL;

                                   /* Buffer points to memory.  */
   buffer = malloc(MAX_LINE_LENGTH);

   if (buffer == NULL)             /* If error ...              */
      {
         perror("malloc");
         exit(EXIT_FAILURE);
      }

   while (gets(buffer) != NULL)    /* While not Ctrl/Z ...      */
      {
                                   /* Allocate for input line.  */
         next_line = calloc(1, sizeof (struct line_rec));

         if (next_line == NULL)
            {
               perror("calloc");
               exit(EXIT_FAILURE);
            }
                                   /* Put line in data area.    */
         next_line-> data = buffer;

         if (last_line == NULL)    /* Reset pointers.           */
            first_line = next_line;
         else
            last_line-> next = next_line;

         last_line = next_line;
                                  /* Allocate space for the     *
                                   *  next input line.          */
         buffer = malloc(MAX_LINE_LENGTH);

         if (buffer == NULL)
            {
               perror("malloc");
               exit(EXIT_FAILURE);
            }
      }
   free(buffer);                  /* Last buffer always unused. */
   next_line = first_line;        /* Pointer to beginning.      */

   while (next_line != NULL);
      {
         puts(next_line -> data); /* Write line to screen.      */
         free(next_line -> data); /* Deallocate a line.         */
         last_line = next_line;
         next_line = next_line-> next;
         free(last_line);
      }

exit(EXIT_SUCCESS);
}

The sample input and output for Example 8-1 are as follows:

$ RUN  EXAMPLE
line one
line two
<Ctrl/Z>
EXIT
line one
line two
$


Previous Page | Next Page | Table of Contents | Index