/************************************************************************ * * * Copyright Digital Equipment Corporation 1998. All rights reserved. * * * * Restricted Rights: Use, duplication, or disclosure by the U.S. * * Government is subject to restrictions as set forth in subparagraph * * (c) (1) (ii) of DFARS 252.227-7013, or in FAR 52.227-19, or in FAR * * 52.227-14 Alt. III, as applicable. * * * * This software is proprietary to and embodies the confidential * * technology of Digital Equipment Corporation. Possession, use, or * * copying of this software and media is authorized only pursuant to a * * valid written license from Digital or an authorized sublicensor. * * * ************************************************************************/ /* chap_8_mem_management.c */ /* 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 the memory used for the structures. */ #include #include #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); }