Simplify comments in mpool.h
[eleutheria.git] / buddy / test2.c
blob0480fa6e65b13b2435b1c58263f834b1185ac189
1 /*
2 * Compile with:
3 * gcc test2.c mpool.c -o test2 -Wall -W -Wextra -ansi -pedantic
4 */
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <time.h> /* for time() in srand() */
10 #include "mpool.h"
12 int main(int argc, char *argv[])
14 mpool_t *mpool;
15 mpret_t mpret;
16 int i, j, **array;
18 /* Check argument count */
19 if (argc != 3) {
20 fprintf(stderr, "Usage: %s nrows ncols\n", argv[0]);
21 exit(EXIT_FAILURE);
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");
28 exit(EXIT_FAILURE);
30 else if (mpret == MPOOL_ERANGE) {
31 fprintf(stderr, "mpool: out of range in mpool_init()\n");
32 exit(EXIT_FAILURE);
34 else if (mpret == MPOOL_EBADVAL) {
35 fprintf(stderr, "mpool: bad value passed to mpool_init()\n");
36 exit(EXIT_FAILURE);
39 /* Initialize random number generator */
40 srand(time(NULL));
42 /* Allocate memory for rows */
43 if ((array = mpool_alloc(mpool, atoi(argv[1]) * sizeof *array)) == NULL) {
44 fprintf(stderr, "mpool: no available block in pool\n");
45 mpool_destroy(mpool);
46 exit(EXIT_FAILURE);
49 /* Allocate memory for columns */
50 for (i = 0; i < atoi(argv[1]); i++) {
51 if ((array[i] = mpool_alloc(mpool,
52 atoi(argv[2]) * sizeof **array)) == NULL) {
53 fprintf(stderr, "mpool: no available block in pool\n");
54 mpool_destroy(mpool);
55 exit(EXIT_FAILURE);
59 /* Fill in matrix with random values and print it */
60 for (i = 0; i < atoi(argv[1]); i++) {
61 for (j = 0; j < atoi(argv[2]); j++) {
62 array[i][j] = rand() % 100;
63 printf("%2d\t", array[i][j]);
65 printf("\n");
69 * Destroy memory pool and free all resources
71 * One, normally, would have to explicitly call mpool_free(),
72 * in order to liberate the allocated blocks one by one.
73 * But since we terminate anyway, just nuke the whole
74 * pool with mpool_destroy()
76 mpool_destroy(mpool);
78 return EXIT_SUCCESS;