home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_10_10 / 1010048b < prev    next >
Text File  |  1992-08-12  |  1KB  |  68 lines

  1. /* Listing 2. */
  2.  
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5.  
  6. #define TEST
  7. #include "listing4.h"
  8.  
  9. /* this function allocates a num_elem array of
  10.    pointers to arrays of integers. it then allocates
  11.    the arrays themselves*/
  12. int **target(int num_elem,int elem_size)
  13. {
  14.   int  **master;
  15.   int  index = 0;
  16.  
  17.   /* allocate an array of pointers */
  18.   master = calloc(num_elem,sizeof(int *));
  19.   if(master != NULL)
  20.   {
  21.      /* allocate the arrays of ints */
  22.      do
  23.      {
  24.         master[index] = calloc(elem_size,sizeof(int));
  25.         if(master[index] == NULL)
  26.         {
  27.            /* back out gracefully */
  28.            return NULL;
  29.         }
  30.      } while(index < num_elem);
  31.      return master;
  32.   }
  33.   else
  34.      return NULL;
  35. }
  36.  
  37. /******** beginning of test code **********/
  38. #if defined( TEST )
  39.  
  40. int testTarget( void )
  41. {
  42.   int  **master;
  43.  
  44.   /* macro defined in Listing 4. This macro must
  45.      follow all local variable declarations and
  46.      precede any code statements. */
  47.   StartTest( "target()" );
  48.  
  49.   /* specify failure on first allocation attempt */
  50.   SetCalloc( 0 );
  51.   if((master = target(10,10)) != NULL)
  52.      ErrorMsg( 1, "Target failed out of memory test");
  53.  
  54.   /* specify failure on second allocation */
  55.   SetCalloc( 1 );
  56.   if((master = target(10,10)) != NULL)
  57.      ErrorMsg( 2, "Target failed out of memory test" );
  58.  
  59.   EndTest;
  60. }
  61.  
  62. main()
  63. {
  64.   if(testTarget() > 0)
  65.      printf("\a%d errors detected in target()\n");
  66. }
  67. #endif /* end of test code */
  68.