3 * gcc test2.c mpool.c -o test2 -Wall -W -Wextra -ansi -pedantic
8 #include <time.h> /* for time() in srand() */
12 int main(int argc
, char *argv
[])
18 /* Check argument count */
20 fprintf(stderr
, "Usage: %s nrows ncols\n", argv
[0]);
24 /* Initialize memory pool with 1024 bytes */
25 mpret
= mpool_init(&mpool
, 10, 5);
26 if (mpret
== MPOOL_ENOMEM
) {
27 fprintf(stderr
, "mpool: not enough memory\n");
30 else if (mpret
== MPOOL_EBADVAL
) {
31 fprintf(stderr
, "mpool: bad value passed to mpool_init()\n");
35 /* Initialize random number generator */
38 /* Allocate memory for rows */
39 if ((array
= mpool_alloc(mpool
, atoi(argv
[1]) * sizeof *array
)) == NULL
) {
40 fprintf(stderr
, "mpool: no available block in pool\n");
45 /* Allocate memory for columns */
46 for (i
= 0; i
< atoi(argv
[1]); i
++) {
47 if ((array
[i
] = mpool_alloc(mpool
, atoi(argv
[2]) * sizeof **array
)) == NULL
) {
48 fprintf(stderr
, "mpool: no available block in pool\n");
54 /* Fill in matrix with random values and print it */
55 for (i
= 0; i
< atoi(argv
[1]); i
++) {
56 for (j
= 0; j
< atoi(argv
[2]); j
++) {
57 array
[i
][j
] = rand() % 100;
58 printf("%2d\t", array
[i
][j
]);
64 * Destroy memory pool and free all resources
66 * One, normally, would have to explicitly call mpool_free(),
67 * in order to liberate the allocated blocks one by one.
68 * But since we terminate anyway, just nuke the whole
69 * pool with mpool_destroy()