3 * gcc test3.c mpool.c mstat.c -o test3 -Wall -W -Wextra -ansi -pedantic
8 #include <string.h> /* for memset() */
9 #include <time.h> /* for time() in srand() */
14 #define MAX_BLOCKS 1000
18 char *pblk
[MAX_BLOCKS
];
21 size_t an
, un
; /* nodes */
22 size_t ab
, ub
; /* blocks */
23 size_t me
, sp
; /* merges, splits */
26 /* Initialize memory pool with 1048576 bytes */
27 mpret
= mpool_init(&mpool
, 20, 5);
28 if (mpret
== MPOOL_ENOMEM
) {
29 fprintf(stderr
, "mpool: not enough memory\n");
32 else if (mpret
== MPOOL_EBADVAL
) {
33 fprintf(stderr
, "mpool: bad value passed to mpool_init()\n");
37 /* Initialize random number generator */
41 for (i
= 0; i
< MAX_BLOCKS
; i
++) {
42 if ((pblk
[i
] = mpool_alloc(mpool
, s
= 1 << (5 + rand() % 7))) == NULL
)
46 * Zero out the allocated block
48 * By doing this, there is a chance that we catch
49 * allocator's bugs, i.e. by writing over the block
50 * and corrupting next block's header.
52 memset(pblk
[i
], 0, s
);
54 /* Every now and then free a block to create holes and invoke merges */
55 if (rand() % 3 == 0) {
56 mpool_free(mpool
, pblk
[i
]);
61 /* Free the rest of the blocks */
62 for (i
= 0; i
< MAX_BLOCKS
; i
++)
64 mpool_free(mpool
, pblk
[i
]);
67 mpool_stat_get_nodes(mpool
, &an
, &un
);
68 mpool_stat_get_bytes(mpool
, &ab
, &ub
);
69 me
= mpool_stat_get_merges(mpool
);
70 sp
= mpool_stat_get_splits(mpool
);
72 printf("avail nodes = %-5u\tused nodes = %-5u\tfree(%%) = %.2f\n",
73 an
, un
, 100.0 * an
/ (an
+ un
));
74 printf("avail bytes = %-5u\tused bytes = %-5u\tfree(%%) = %.2f\n",
75 ab
, ub
, 100.0 * ab
/ (ab
+ ub
));
76 printf("splits = %-5u\tmerges = %-5u\n",
79 /* Destroy memory pool and free all resources */