/* mp5test.c; test program for MP5 */ /* exercises mymalloc() and myfree() on a heap of size HEAPSIZE (see below) * detects heap corruption fairly well, aborts test if corruption detected * gives statistics about heap use if tests passed successfully */ #include #include #include "myheap.h" #define MAXBLOCKS 1024 #define MAXSIZE 1024 #define TRIALS (MAXBLOCKS * 16) #define HEAPSIZE ((MAXBLOCKS / 2) * (MAXSIZE / 3)) void * block[MAXBLOCKS]; main(){ /* count number of each kind of aciton taken */ int allocations = 0; int allocationfailures = 0; int deallocations = 0; /* some statistics to keep */ int demand = 0; int maxdemand = 0; int allocd = 0; int maxallocd = 0; int i; /* initialize */ for (i = 0; i < MAXBLOCKS; i++) block[i] = NULL; heapinit(HEAPSIZE); /* this was missing */ /* test */ for (i = 0; i < TRIALS; i++) { int j = random() % MAXBLOCKS; int * p = block[j]; /* do one allocation or deallocation allocated blocks */ if (p == NULL) { /* allocate a block */ int s = random() % ((random() % MAXSIZE) + 1); int k = 0; if (s < sizeof(int)) s = sizeof(int); p = mymalloc(s); block[j] = p; if (p != NULL) { /* keep statistics */ allocations++; demand = demand + s; if (demand > maxdemand) maxdemand = demand; allocd++; if (allocd > maxallocd) maxallocd = allocd; /* initialize block */ while (s > 0) { p[k] = s; s = s - sizeof(int); k = k + 1; } } else { /* keep statistics */ allocationfailures++; } } else { /* deallocate block p */ int k = 0; int s = p[0]; /* keep statistics */ demand = demand - s; allocd--; /* check that the block is unchanged as initialized */ while (s > 0) { if (p[k] != s) { fprintf(stderr, "deallocate detected heap" " corruption at trial number" " %d; deallocations: %d\n", i, deallocations ); exit( EXIT_FAILURE ); } s = s - sizeof(int); k = k + 1; } myfree( p ); deallocations++; block[j] = NULL; } } /* report on successful test */ fprintf(stderr, "Test program conducted %d trials:\n" " %d allocations, %d failed allocations," " and %d deallocations.\n", TRIALS, allocations, allocationfailures, deallocations ); fprintf(stderr, "at maximum %d bytes out of a heap of size %d were allocated;\n" " at termination, %d bytes were allocated.\n", maxdemand, HEAPSIZE, demand ); fprintf(stderr, "at maximum, %d blocks were allocated out of %d possible;\n" " at termination, %d blocks were allocated.\n", maxallocd, MAXBLOCKS, allocd ); }