Add stress test case
[eleutheria.git] / malloc / test3.c
blobbf8d0361cfd9d2d49aa40b46725cd43b9679d214
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h> /* for memset() */
4 #include <time.h> /* for time() in srand() */
6 #include "mpool.h"
7 #include "mstat.h"
9 #define MAX_BLOCKS 1000
11 int main(void)
13 char *pblk[MAX_BLOCKS];
14 mpool_t *mpool;
15 mpret_t mpret;
16 size_t an, un; /* nodes */
17 size_t ab, ub; /* blocks */
18 size_t me, sp; /* merges, splits */
19 size_t i, s;
21 /* Initialize memory pool with 1048576 bytes */
22 mpret = mpool_init(&mpool, 20, 5);
23 if (mpret == MPOOL_ENOMEM) {
24 fprintf(stderr, "mpool: not enough memory\n");
25 exit(EXIT_FAILURE);
27 else if (mpret == MPOOL_EBADVAL) {
28 fprintf(stderr, "mpool: bad value passed to mpool_init()\n");
29 exit(EXIT_FAILURE);
32 /* Initialize random number generator */
33 srand(time(NULL));
35 /* Allocate blocks */
36 for (i = 0; i < MAX_BLOCKS; i++) {
37 if ((pblk[i] = mpool_alloc(mpool, s = 1 << (5 + rand() % 7))) == NULL)
38 break;
41 * Zero out the allocated block
43 * By doing this, there is a chance that we catch
44 * allocator's bugs, i.e. by writing over the block
45 * and corrupting next block's header.
47 memset(pblk[i], 0, s);
49 /* Every now and then free a block to create holes and invoke merges */
50 if (rand() % 3 == 0) {
51 mpool_free(mpool, pblk[i]);
52 pblk[i] = NULL;
56 /* Free the rest of the blocks */
57 for (i = 0; i < MAX_BLOCKS; i++)
58 if (pblk[i] != NULL)
59 mpool_free(mpool, pblk[i]);
61 /* Dump statistics */
62 mpool_stat_get_nodes(mpool, &an, &un);
63 mpool_stat_get_bytes(mpool, &ab, &ub);
64 me = mpool_stat_get_merges(mpool);
65 sp = mpool_stat_get_splits(mpool);
67 printf("avail nodes = %-5u\tused nodes = %-5u\tfree(%%) = %.2f\n", an, un, 100.0 * an / (an + un));
68 printf("avail bytes = %-5u\tused bytes = %-5u\tfree(%%) = %.2f\n", ab, ub, 100.0 * ab / (ab + ub));
69 printf("splits = %-5u\tmerges = %-5u\n", sp, me);
71 /* Destroy memory pool and free all resources */
72 mpool_destroy(mpool);
74 return EXIT_SUCCESS;