xref: /freebsd/tools/test/malloc/main.c (revision a64729f5077d77e13b9497cb33ecb3c82e606ee8)
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <unistd.h>
5 
6 u_long NBUCKETS		= 2000;
7 u_long NOPS		= 200000;
8 u_long NSIZE		= (16*1024);
9 
10 char **foo;
11 
12 int
13 main(int argc, char **argv)
14 {
15     u_long i,j,k;
16 
17     if (argc > 1) NOPS     = strtoul(argv[1],0,0);
18     if (argc > 2) NBUCKETS = strtoul(argv[2],0,0);
19     if (argc > 3) NSIZE	   = strtoul(argv[3],0,0);
20     printf("BRK(0)=%p ", sbrk(0));
21     foo = malloc(sizeof(*foo) * NBUCKETS);
22     memset(foo, 0, sizeof(*foo) * NBUCKETS);
23     for (i = 1; i <= 4096; i *= 2) {
24         for (j = 0; j < 40960/i && j < NBUCKETS; j++) {
25 	    foo[j] = malloc(i);
26         }
27         for (j = 0; j < 40960/i && j < NBUCKETS; j++) {
28 	    free(foo[j]);
29 	    foo[j] = NULL;
30         }
31     }
32 
33     for (i = 0; i < NOPS; i++) {
34 	j = random() % NBUCKETS;
35 	k = random() % NSIZE;
36 	foo[j] = realloc(foo[j], k & 1 ? 0 : k);
37 	if (k & 1 || k == 0) {
38 		/*
39 		 * Workaround because realloc return bogus pointer rather than
40 		 * NULL if passed zero length.
41 		 */
42 		foo[j] = NULL;
43 	}
44 	if (foo[j])
45 	    foo[j][0] = 1;
46     }
47     printf("BRK(1)=%p ", sbrk(0));
48     for (j = 0; j < NBUCKETS; j++) {
49 	if (foo[j]) {
50 	    free(foo[j]);
51 	    foo[j] = NULL;
52 	}
53     }
54     printf("BRK(2)=%p NOPS=%lu NBUCKETS=%lu NSIZE=%lu\n",
55 	sbrk(0), NOPS, NBUCKETS, NSIZE);
56     return 0;
57 }
58