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