Honour 80 cols per line limit
[eleutheria.git] / buddy / test2.c
bloba59418b2606823be8a567041309d2ad7e56ecf54
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_EBADVAL) {
31 fprintf(stderr, "mpool: bad value passed to mpool_init()\n");
32 exit(EXIT_FAILURE);
35 /* Initialize random number generator */
36 srand(time(NULL));
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");
41 mpool_destroy(mpool);
42 exit(EXIT_FAILURE);
45 /* Allocate memory for columns */
46 for (i = 0; i < atoi(argv[1]); i++) {
47 if ((array[i] = mpool_alloc(mpool,
48 atoi(argv[2]) * sizeof **array)) == NULL) {
49 fprintf(stderr, "mpool: no available block in pool\n");
50 mpool_destroy(mpool);
51 exit(EXIT_FAILURE);
55 /* Fill in matrix with random values and print it */
56 for (i = 0; i < atoi(argv[1]); i++) {
57 for (j = 0; j < atoi(argv[2]); j++) {
58 array[i][j] = rand() % 100;
59 printf("%2d\t", array[i][j]);
61 printf("\n");
65 * Destroy memory pool and free all resources
67 * One, normally, would have to explicitly call mpool_free(),
68 * in order to liberate the allocated blocks one by one.
69 * But since we terminate anyway, just nuke the whole
70 * pool with mpool_destroy()
72 mpool_destroy(mpool);
74 return EXIT_SUCCESS;