home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tyc / list20_4.c < prev    next >
C/C++ Source or Header  |  1993-10-16  |  1KB  |  50 lines

  1.  /* Using free() to release allocated dynamic memory. */
  2.  
  3.  #include <stdio.h>
  4.  #include <stdlib.h>
  5.  #include <string.h>
  6.  
  7.  #define BLOCKSIZE 30000
  8.  
  9.  main()
  10.  {
  11.      void *ptr1, *ptr2;
  12.  
  13.      /* Allocate one block. */
  14.  
  15.      ptr1 = malloc(BLOCKSIZE);
  16.  
  17.      if (ptr1 != NULL)
  18.          printf("\nFirst allocation of %d bytes successful.", BLOCKSIZE);
  19.      else
  20.      {
  21.          printf("\nAttempt to allocate %d bytes failed.", BLOCKSIZE);
  22.          exit(1);
  23.      }
  24.  
  25.      /* Try to allocate another block. */
  26.  
  27.      ptr2 = malloc(BLOCKSIZE);
  28.  
  29.      if (ptr2 != NULL)
  30.      {
  31.          /* If allocation successful, print message and exit. */
  32.  
  33.          printf("\nSecond allocation of %d bytes successful.",
  34.                  BLOCKSIZE);
  35.          exit(0);
  36.      }
  37.  
  38.      /* If not successful, free the first block and try again. */
  39.  
  40.      printf("\nSecond attempt to allocate %d bytes failed.", BLOCKSIZE);
  41.      free(ptr1);
  42.      printf("\nFreeing first block.");
  43.  
  44.      ptr2 = malloc(BLOCKSIZE);
  45.  
  46.      if (ptr2 != NULL)
  47.          printf("\nAfter free(), allocation of %d bytes successful.",
  48.                  BLOCKSIZE);
  49.  }
  50.