/* mp6test.c */ /* a heap exerciser */ #include #include #include #include "mymalloc.h" /* number of malloc/free trials to run */ #define TRIALS 10000 /* number of pointers to allocate (average heap use will be 1/2 this) */ #define POINTERS 1000 /* average block size for allocation, in bytes */ #define SIZES 1000 /* pointers to objects on the heap */ static int * pointer[ POINTERS ] = {NULL}; /* each object begins with its size (an intptr_t) */ main(){ int trial; /* for loop counter */ /* record of the demand on the heap */ long int maxdemand = 0; /* maximum encountered */ long int curdemand = 0; /* current value*/ long int sumdemand = 0; /* integrated current demand */ int mallocs = 0; /* count malloc calls */ long int summallocs = 0;/* integrated amount allocated */ srandom( 12 ); /* make things repeatable */ for (trial = 0; trial < TRIALS; trial++) { int item = random() % POINTERS; int * p = pointer[item]; if (p == NULL) { /* we allocate */ int size; /* block size to allocate */ int i; /* index for initializing block */ /* work in words, not bytes, make a long-tail */ #define WORDS (SIZES / sizeof( int )) #define PEAK ((WORDS * 400)/ 100) /* make long-tail on size distribution */ size = (random() % PEAK) + 1; size = (random() % size) + 1; /* now we get a block */ p = mymalloc( size * sizeof( int ) ); if (p != NULL) { /* expected case */ mallocs = mallocs + 1; p[0] = size; for (i = 1; i < size; i++) { p[i] = i; } curdemand = curdemand + (size * sizeof( int )); summallocs = summallocs + (size * sizeof( int )); } else { /* should never occur */ printf( "allocate failure\n" ); fflush( stdout ); } pointer[item] = p; } else { /* we deallocate */ int i = 0; /* index for checking block */ int size = p[0]; for (i = 1; i < size; i++) { if (p[i] != i) printf( "bad at %d\n", trial ); } myfree( p ); pointer[item] = NULL; curdemand = curdemand - (size * sizeof( int )); } /* gather statistics */ if (curdemand > maxdemand) maxdemand = curdemand; sumdemand = sumdemand + curdemand; } printf( "completed %d trials\n", TRIALS ); printf( " %d mallocs\n", mallocs ); printf( " %d frees\n", TRIALS-mallocs ); printf( "maximum demand was %d bytes\n", maxdemand); printf( "average demand was %d bytes\n", sumdemand / TRIALS ); printf( "average block size %d bytes\n", summallocs / mallocs ); }