Listing 4 test calloc — This module provides malloc and calloc shell functions to enable test code to force malloc and calloc to fail. The test code should call either SetCalloc or SetMalloc to specify the number of times calloc and malloc should succeed before failing.

#include <stddef.h>
#include <stdlib.h>

static int  callocPass;
static int  mallocPass;

/* set calloc counter */
void    SetCalloc( int passes )
{
  callocPass = passes;
}

/* set malloc counter */
void    SetMalloc( int passes )
{
  mallocPass = passes;
}

/* count down to 0 and then fail to allocate memory */
void *testCalloc(size_t numElems,size_t elemSize)
{
  #undef calloc
  if ( callocPass > 0 )
  {
    --callocPass;
    return calloc( numElems, elemSize );
  }
  else
    return NULL;
}

/* count down to 0 and then fail to allocate memory */
void    *testMalloc( size_t numElems )
{
  #undef malloc
  if ( mallocPass > 0 )
  {
    --mallocPass;
    return malloc( numElems );
  }
  else
    return NULL;
}
/* End of File */