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_ERANGE
) {
33 fprintf(stderr
, "mpool: out of range in mpool_init()\n");
36 else if (mpret
== MPOOL_EBADVAL
) {
37 fprintf(stderr
, "mpool: bad value passed to mpool_init()\n");
41 /* Initialize random number generator */
45 for (i
= 0; i
< MAX_BLOCKS
; i
++) {
46 if ((pblk
[i
] = mpool_alloc(mpool
, s
= 1 << (5 + rand() % 7))) == NULL
)
50 * Zero out the allocated block
52 * By doing this, there is a chance that we catch
53 * allocator's bugs, i.e. by writing over the block
54 * and corrupting next block's header.
56 memset(pblk
[i
], 0, s
);
58 /* Every now and then free a block to create holes and invoke merges */
59 if (rand() % 3 == 0) {
60 mpool_free(mpool
, pblk
[i
]);
65 /* Free the rest of the blocks */
66 for (i
= 0; i
< MAX_BLOCKS
; i
++)
68 mpool_free(mpool
, pblk
[i
]);
71 mpool_stat_get_nodes(mpool
, &an
, &un
);
72 mpool_stat_get_bytes(mpool
, &ab
, &ub
);
73 me
= mpool_stat_get_merges(mpool
);
74 sp
= mpool_stat_get_splits(mpool
);
76 printf("avail nodes = %-5u\tused nodes = %-5u\tfree(%%) = %.2f\n",
77 an
, un
, 100.0 * an
/ (an
+ un
));
78 printf("avail bytes = %-5u\tused bytes = %-5u\tfree(%%) = %.2f\n",
79 ab
, ub
, 100.0 * ab
/ (ab
+ ub
));
80 printf("splits = %-5u\tmerges = %-5u\n",
83 /* Destroy memory pool and free all resources */