Add comment clarifying prop_array_t data type
[eleutheria.git] / malloc / test2.c
blob964e20bb622c6597ff0c0ea88e9b15bf928b0ef7
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <time.h> /* for time() in srand() */
5 #include "mpool.h"
7 int main(int argc, char *argv[])
9 mpool_t *mpool;
10 mpret_t mpret;
11 int i, j, **array;
13 /* Check argument count */
14 if (argc != 3) {
15 fprintf(stderr, "usage: %s nrows ncols\n", argv[0]);
16 exit(EXIT_FAILURE);
19 /* Initialize memory pool with 1024 bytes */
20 mpret = mpool_init(&mpool, 10, 5);
21 if (mpret == MPOOL_ENOMEM) {
22 fprintf(stderr, "mpool: not enough memory\n");
23 exit(EXIT_FAILURE);
25 else if (mpret == MPOOL_EBADVAL) {
26 fprintf(stderr, "mpool: bad value passed to mpool_init()\n");
27 exit(EXIT_FAILURE);
30 /* Initialize random number generator */
31 srand(time(NULL));
33 /* Allocate memory for rows */
34 if ((array = mpool_alloc(mpool, atoi(argv[1]) * sizeof *array)) == NULL) {
35 fprintf(stderr, "mpool: no available block in pool\n");
36 mpool_destroy(mpool);
37 exit(EXIT_FAILURE);
40 /* Allocate memory for columns */
41 for (i = 0; i < atoi(argv[1]); i++) {
42 if ((array[i] = mpool_alloc(mpool, atoi(argv[2]) * sizeof **array)) == NULL) {
43 fprintf(stderr, "mpool: no available block in pool\n");
44 mpool_destroy(mpool);
45 exit(EXIT_FAILURE);
49 /* Fill in matrix with random values and print it */
50 for (i = 0; i < atoi(argv[1]); i++) {
51 for (j = 0; j < atoi(argv[2]); j++) {
52 array[i][j] = rand() % 100;
53 printf("%2d\t", array[i][j]);
55 printf("\n");
59 * Destroy memory pool and free all resources
61 * One, normally, would have to explicitly call mpool_free(),
62 * in order to liberate the allocated blocks one by one.
63 * But since we terminate anyway, just nuke the whole
64 * pool with mpool_destroy()
66 mpool_destroy(mpool);
68 return EXIT_SUCCESS;